如何从 Python 字典中的值中获取键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45635242/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:10:54  来源:igfitidea点击:

How to get the key from value in a dictionary in Python?

python

提问by Peter

d[key] = value

but how to get the keys from value?

但是如何从值中获取键呢?

For example:

例如:

a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10

print(do_something with 10 to get ["hot", "hugs"])

回答by John Kugelman

You can write a list comprehension to pull out the matching keys.

您可以编写一个列表推导式来提取匹配的键。

print([k for k,v in a.items() if v == b])

回答by Mohamed Ali JAMAOUI

Something like this can do it:

像这样的事情可以做到:

for key, value in a.iteritems():
    if value == 10:
        print key

If you want to save the associated keys to a value in a list, you edit the above example as follows:

如果要将关联的键保存到列表中的值,请按如下方式编辑上面的示例:

keys = []
for key, value in a.iteritems():
    if value == 10:
        print key
        keys.append(key)

You can also do that in a list comprehension as pointed out in an other answer.

您也可以在其他答案中指出的列表理解中做到这一点。

b = 10 
keys = [key for key, value in a.iteritems() if value == b]

Note that in python 3, dict.itemsis equivalent to dict.iteritemsin python 2, check this for more details: What is the difference between dict.items() and dict.iteritems()?

请注意,在 python 3 中,dict.items相当于dict.iteritems在 python 2 中,查看更多详细信息:dict.items() 和 dict.iteritems() 之间有什么区别?