如何从值中获取密钥?
我的词:
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
预期产出:
Normal UK project
实际输出:
French project
UK Omnibus project
German project
Normal UK project
如何修复我的代码?
答案 0 :(得分:7)
问题是字典中值的类型不同,使得使用字典变得更加困难,不仅仅是在这种情况下。虽然Python允许这样做,但你真的应该考虑统一字典中的类型,例如把它们全部列出来。您只需一行代码即可完成此操作:
countries = {key: val if isinstance(val, list) else [val]
for key, val in countries.items()}
现在,每个字符串都包含在一个列表中,您现有的代码将正常运行。
或者,如果您必须在其当前表单中使用字典,则可以调整查找功能:
for k, v in countries.items():
if "1" == v or isinstance(v, list) and "1" in v:
print k
答案 1 :(得分:6)
c={}
- 任何字典
a(值) - 需要知道这个键
key=list(c.keys())[list(c.values()).index(a)]]
答案 2 :(得分:3)
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"
如果你想让我稍微缩短一点,我可能会做
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"
答案 3 :(得分:3)
以下代码通过使用list comprehensions和dic.items()提供了通过某种值获取字典键的另一个简短版本:
keys_have_value = [k for k,v in dic.items() if v=="1"]
答案 4 :(得分:2)
您的半功能代码返回其他值,因为条目如下:
"Normal UK project" : "1",
..然后"1" in v
检查字符串是否包含“1”字符,而条目如下:
"Nordic project" : ["11","12","13","14"],
..然后它将检查列表是否包含元素“1”。
in
运算符适用于字符串和列表,但方式不同:
>>> "1" in "123"
True
>>> "1" in ["123", "blah"]
False
>>> "1" in ["1", "blah"]
True
理想情况下,您的数据会更加一致 - 所有列表或所有字符串:
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
答案 5 :(得分:0)
我个人认为使用in
并且函数values
更容易。
print 1 in {1:"123", 2:"blah"}
print "blah" in {1:"123", 2:"blah"}.values()
输出是:
True
True
答案 6 :(得分:0)
def get_Value(dic,value):
for name in dic:
if dic[name] == value:
return name