tags:

views:

161

answers:

3

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?

+13  A: 
if key in array:
  # do something

Associative arrays are called in Python dictionaries and you can learn more about them here:
http://docs.python.org/library/stdtypes.html#dict

rawicki
And, be sure to put the key name in quotes if it's a string.
Alex JL
A: 

another method is has_key() (if still using 2.X)

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
ghostdog74
`has_key` is deprecated, removed in python 3, and half as fast in python 2
aaronasterling
yes, but not in 2.X.
ghostdog74
yes it is deprecated in 2.x and yes it is half as fast in python 2.x.
aaronasterling
no, its not for <=2.5+.
ghostdog74
deprecated applies to all new code. once it's deprecated, don't use it anymore.
aaronasterling
the form 'key in dict' has existed since 2.2
RevolXadda
we could go on and on about this, the fact remains, its still an alternative option for <=2.5.
ghostdog74
+1  A: 

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

Marc
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.
aaronasterling