Python 如何检查字典中是否存在键?

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

How can I check if a key exists in a dictionary?

python

提问by aneuryzm

Let's say I have an associative array like so: {'key1': 22, 'key2': 42}.

比方说,我有一个关联数组,像这样:{'key1': 22, 'key2': 42}

How can I check if key1exists in the dictionary?

如何检查key1字典中是否存在?

采纳答案by Rafa? Rawicki

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

关联数组在 Python 中称为字典,您可以在stdtypes 文档中了解有关它们的更多信息

回答by ghostdog74

Another method is has_key()(if still using Python 2.X):

另一种方法是has_key()(如果仍在使用 Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

回答by Marc

If you want to retrieve the key's value if it exists, you can also use

如果要检索键的值(如果存在),也可以使用

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

如果要在键不存在时检索默认值,请使用 value = a.get(key, default_value). 如果您想同时设置默认值以防键不存在,请使用 value = a.setdefault(key, default_value).