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


Question

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

How can I check if key1 exists in the dictionary?

1
287
4/20/2019 1:29:27 AM

Accepted Answer

if key in array:
  # do something

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

533
12/12/2015 10:51:25 PM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon