按值、字典、python 获取键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23295315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get Key by value, dict, python
提问by Boosted_d16
How can I get a key from a value?
如何从值中获取键?
my dict:
我的字典:
countries = {
"Normal UK project" : "1",
"UK Omnibus project" : "1-Omni",
"Nordic project" : ["11","12","13","14"],
"German project" : "21",
"French project" : "31"
}
my semi functioning code:
我的半功能代码:
for k, v in countries.items():
if "1" in v:
print k
expected output:
预期输出:
Normal UK project
actual output:
实际输出:
French project
UK Omnibus project
German project
Normal UK project
How can I fix my code?
我该如何修复我的代码?
采纳答案by tobias_k
The problem is that the types of the values in the dictionary are not the same, making it much more difficult to use the dictionary, not only in this scenario. While Python allows this, you really should consider unifying the types in the dictionary, e.g. make them all lists. You can do so in just one line of code:
问题是字典中值的类型不一样,这使得使用字典变得更加困难,不仅在这种情况下。虽然 Python 允许这样做,但您确实应该考虑统一字典中的类型,例如将它们全部列出。您只需一行代码即可完成此操作:
countries = {key: val if isinstance(val, list) else [val]
for key, val in countries.items()}
Now, each single string is wrapped into a list and your existing code will work correctly.
现在,每个字符串都被包装到一个列表中,您现有的代码将正常工作。
Alternatively, if you have to use the dictionary in it's current form, you can adapt your lookup function:
或者,如果您必须使用当前形式的字典,您可以调整您的查找功能:
for k, v in countries.items():
if "1" == v or isinstance(v, list) and "1" in v:
print k
回答by thefourtheye
def keys_of_value(dct, value):
for k in dct:
if isinstance(dct[k], list):
if value in dct[k]:
return k
else:
if value == dct[k]:
return k
assert keys_of_value(countries, "12") == "Nordic project"
assert keys_of_value(countries, "1") == "Normal UK project"
If you want me to shorten it a little bit, I might do
如果你想让我把它缩短一点,我可能会这样做
from operator import eq, contains
def keys_of_value(dct, value, ops = (eq, contains)):
for k in dct:
if ops[isinstance(dct[k], list)](dct[k], value):
return k
assert keys_of_value(countries, "12") == "Nordic project"
assert keys_of_value(countries, "1") == "Normal UK project"
回答by dbr
Your semi-functioning code is returning the other values because with entries like:
您的半功能代码正在返回其他值,因为具有以下条目:
"Normal UK project" : "1",
..then "1" in v
checks if the string contains the "1" character, whereas with entries like:
..then"1" in v
检查字符串是否包含“1”字符,而条目如下:
"Nordic project" : ["11","12","13","14"],
..then it will check if the list contains an element "1".
..然后它将检查列表是否包含元素“1”。
The in
operator works on both strings and lists, but in a different manner:
该in
运算符适用于字符串和列表,但方式不同:
>>> "1" in "123"
True
>>> "1" in ["123", "blah"]
False
>>> "1" in ["1", "blah"]
True
Ideally your data would be more consistent - all lists, or all strings:
理想情况下,您的数据会更加一致 - 所有列表或所有字符串:
countries = {
"Normal UK project" : ["1"],
"UK Omnibus project" : ["1-Omni"],
"Nordic project" : ["11","12","13","14"],
"German project" : ["21"],
"French project" : ["31"]
}
for k, v in countries.items():
if "1" in v:
print k
回答by Ehsan Ab
I personally think using in
and the function values
is easier.
我个人认为使用in
和功能values
更容易。
print 1 in {1:"123", 2:"blah"}
print "blah" in {1:"123", 2:"blah"}.values()
Output is:
输出是:
True
True
回答by Юра Панарин
c={}
- any dict
a(value) - need know this key
c={}
- 任何 dict
a(value) - 需要知道这个键
key=list(c.keys())[list(c.values()).index(a)]]
回答by Raj Damani
def get_Value(dic,value):
for name in dic:
if dic[name] == value:
return name
回答by Serjik
The following code provide another and short version of getting dictionary keys by some value, by using list comprehensions and dic.items():
以下代码通过使用列表推导式和 dic.items() 提供了另一种通过某个值获取字典键的简短版本:
keys_have_value = [k for k,v in dic.items() if v=="1"]