如何检查字典中是否存在密钥? [重复]

时间:2022-03-05 23:44:53

Possible Duplicate:
Check if a given key already exists in a dictionary

可能重复:检查字典中是否已存在给定键

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

假设我有一个关联数组,如:{'key1':22,'key2':42}。

How can I check if key1 exists in the dictionary?

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

3 个解决方案

#1


466  

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文档中了解有关它们的更多信息。

#2


51  

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

#3


38  

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)。

#1


466  

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文档中了解有关它们的更多信息。

#2


51  

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

#3


38  

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)。