Python: how can I check if the key of an dictionary exists?
Possible Duplicate:
What is a good way to test if a Key exists in Python Dictionary
Let's say I have an associative array like so: {'key1': 22, 'key2': 42}
.
How can I check if key1
exists in the dictionary?
if key in array:
# do something
关联数组在Python中称为字典,您可以在stdtypes文档中了解更多关于它们的信息。
另一种方法是has_key()(如果仍然使用2.X)
>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
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)
.
上一篇: 如何测试字典是否包含特定的密钥?