d[key] = value
但是如何从值中获取键呢?
例如:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
d[key] = value
但是如何从值中获取键呢?
例如:
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
等同于Python 2中的dict.iteritems
。有关更多详细信息,请查看此处:What is the difference between dict.items() and dict.iteritems()?