d[key] = value
但如何从价值中获得钥匙?如何从Python中的字典中获取键值?
例如:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
d[key] = value
但如何从价值中获得钥匙?如何从Python中的字典中获取键值?
例如:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
你可以写一个列表理解拉出匹配的密钥。
print([k for k,v in a.items() if v == b])
像这样的事情可以做:
for key, value in a.iteritems():
if value == 10:
print key
如果你想关联的密钥保存到列表中的一个值,您可以编辑上面的例子如下:
keys = []
for key, value in a.iteritems():
if value == 10:
print key
keys.append(key)
您也可以在列表理解中做到这一点,正如其他答案中指出的那样。
b = 10
keys = [key for key, value in a.iteritems() if value == b]
注意的是Python 3,dict.items
相当于dict.iteritems
在Python 2,请在此了解更多详情:What is the difference between dict.items() and dict.iteritems()?
最接近你会得到OP想要的东西 – maestromusica
这不是什么地图被造的,它应该是周围的其他方法。 为什么你需要通过它们的值来查找条目? – Altoyyr