408

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
  • 1
    In python 3 you can just use 'key1' in {'key1': 22, 'key2': 42}.keys() refer to the keys() method in Dictionary Commented Feb 10, 2020 at 20:13

3 Answers 3

727
if key in array: # do something 

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

Sign up to request clarification or add additional context in comments.

13 Comments

And, be sure to put the key name in quotes if it's a string.
@astroanu if key not in array
Where did the word "array" come from in this answer?
As accepted answers go, this one is horrible. It in no way answers the question and is nothing more than a condescending link to the documentation. It is sad that Google ranks this so highly.
@cstrutton Please suggest improvements. At the moment of writing this answer I didn't feel more details is necessary.
|
65

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

3 Comments

It should be noted that you should only use the try/except case if you expect that the key will be present approaching 100% of the time. otherwise, if in is prettier and more efficient. +1 for mentioning the other possibilities.
Interesting, I remember that I read somewhere in the official docs that it is better to ask for forgiveness than permission...
from point of view of performance , try/expect is better if you are dealing with dict with many keys
63

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

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

8 Comments

has_key is deprecated, removed in python 3, and half as fast in python 2
yes it is deprecated in 2.x and yes it is half as fast in python 2.x.
deprecated applies to all new code. once it's deprecated, don't use it anymore.
the form 'key in dict' has existed since 2.2
we could go on and on about this, the fact remains, its still an alternative option for <=2.5.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.