Let's say I have an associative array like so: {'key1': 22, 'key2': 42}.
How can I check if key1 exists in the dictionary?
if key in array: # do something Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.
if key not in arrayIf 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).
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.Another method is has_key() (if still using Python 2.X):
>>> a={"1":"one","2":"two"} >>> a.has_key("1") True has_key is deprecated, removed in python 3, and half as fast in python 2
'key1' in {'key1': 22, 'key2': 42}.keys()refer to thekeys()method in Dictionary