Python字典获取Key的值

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

Python Dictionary get value of Key

pythondictionary

提问by Aaron

Is there a way to get the value of the key, not the key valuein a dictionary? for example:

有没有一种方法来获得关键的价值,而不是键值在字典?例如:

d = {"testkey": "testvalue"}
print(d.get("testkey"))
#OUTPUT: "testvalue"

Is there a way to get the String "testkey"? I will have no way of knowing what the String returned will be in the end. Would it be more beneficial to use a list instead of a dictionary?

有没有办法获得字符串“testkey”?我将无法知道返回的字符串最终会是什么。使用列表而不是字典会更有益吗?

回答by Idos

You are looking for the keys()function (used as d.keys()).
You may also use this:

您正在寻找keys()函数(用作d.keys())。
你也可以使用这个:

for key in d:
   print "key: %s , value: %s" % (key, d[key])

for all the information.

对于所有信息。

回答by elegent

First note that dictsare not intended to be used this way. Anyway you can use a simple list comprehension and the items()method, since there could be more than one result:

首先请注意,dicts不打算以这种方式使用。无论如何,您可以使用简单的列表理解和items()方法,因为结果可能不止一个:

[key for key, val in d.items() if val == someValue]

For instance:

例如:

>>> myDict = {1:"egg", "Answer":42, 8:14, "foo":42}
>>> [key for key, val in myDict.items() if val == 42]
['Answer', 'foo']