在 Python 字典中查找所有具有相同值的键

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

Finding All The Keys With the Same Value in a Python Dictionary

pythondictionary

提问by Cobie Fisher

Let's say I have a dictionary:

假设我有一本字典:

dict = {"Jim": "y", "Bob": "y", "Ravioli": "n"} #etc...

I want to print out all the keys with the value "y" (i.e: "Jim", "Bob"). How do I do this (in the easiest way for a noobie like me to understand)?

我想打印出所有值为“y”的键(即:“Jim”、“Bob”)。我该怎么做(以我这样的菜鸟最容易理解的方式)?

*P.S. This question has already been answered here on SO, but the solutions only return one value and not all (and others I didn't understand).

*PS 这个问题已经在 SO 上得到了回答,但解决方案只返回一个值而不是全部(以及其他我不理解的值)。

PPS. It looks like everyone seems to think that it is a duplicate, but SO won't let me delete my question because it has an answer. ;(*

聚苯乙烯。看起来每个人似乎都认为它是重复的,但 SO 不会让我删除我的问题,因为它有答案。;(*

回答by Rahul K P

Try this,

尝试这个,

In [26]: [k for k,v in dict1.items() if v == 'y']
Out[26]: ['Bob', 'Jim']

And please don't use dictas a variable name.

并且请不要dict用作变量名。