How can I check if a key exists in a dictionary? [duplicate] How can I check if a key exists in a dictionary? [duplicate] python python

How can I check if a key exists in a dictionary? [duplicate]


if key in array:  # do something

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


Another method is has_key() (if still using Python 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, usevalue = a.get(key, default_value).If you want to set the default value at the same time in case the key does not exist, usevalue = a.setdefault(key, default_value).