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

Python

Python Problem Overview


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

How can I check if key1 exists in the dictionary?

Python Solutions


Solution 1 - Python

if key in array:
  # do something

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

Solution 2 - Python

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

Solution 3 - Python

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaneuryzmView Question on Stackoverflow
Solution 1 - PythonRafał RawickiView Answer on Stackoverflow
Solution 2 - PythonMarcView Answer on Stackoverflow
Solution 3 - Pythonghostdog74View Answer on Stackoverflow