398

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

How can I check if key1 exists in the dictionary?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • 1
    In python 3 you can just use `'key1' in {'key1': 22, 'key2': 42}.keys()` refer to the `keys()` method in [Dictionary](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) – Eat at Joes Feb 10 '20 at 20:13

3 Answers3

712
if key in array:
  # do something

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

mkobit
  • 43,979
  • 12
  • 156
  • 150
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
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).

Marc
  • 4,327
  • 4
  • 30
  • 46
  • 17
    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 Oct 02 '10 at 13:37
  • Interesting, I remember that I read somewhere in the official docs that it is better to ask for forgiveness than permission... – Yannic Hamann Jan 15 '20 at 06:36
  • from point of view of performance , try/expect is better if you are dealing with dict with many keys – Avo Asatryan Mar 03 '20 at 07:52
63

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

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 38
    `has_key` is deprecated, removed in python 3, and half as fast in python 2 – aaronasterling Oct 02 '10 at 11:10
  • 7
    yes it is deprecated in 2.x and yes it is half as fast in python 2.x. – aaronasterling Oct 02 '10 at 11:44
  • 8
    deprecated applies to all new code. once it's deprecated, don't use it anymore. – aaronasterling Oct 02 '10 at 12:40
  • 6
    the form 'key in dict' has existed since 2.2 – Tim W. Oct 02 '10 at 13:01
  • 11
    we could go on and on about this, the fact remains, its still an alternative option for <=2.5. – ghostdog74 Oct 02 '10 at 14:15
  • `has_key` is deprecated, use `if mykey in mydict:` – Pedro Lobito Mar 21 '18 at 15:13
  • 1
    **2018**: you can use `.__contains__` instead of `has_key` (available in Python [2](https://docs.python.org/2/reference/datamodel.html#object.__contains__) and [3](https://docs.python.org/3/reference/datamodel.html#object.__contains__)) - I'm finding it useful to write one liners like `foo = mydict['foo'] if mydict.__contains__('foo') else 'bar'` – ron_g Jan 08 '19 at 09:56
  • 2
    @rong even simpler you can use `foo = mydict.get('foo', 'bar')`. The `in` operator calls `__contains__` so this is just more verbose. – anthonybell Apr 05 '19 at 21:24