Check if a given key already exists in a dictionary
You can test for the presence of a key in a dictionary, using the in keyword:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict()
type to be of interest.
In older code, you may also find some uses of has_key()
, a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name
, instead).
Use key in my_dict
directly instead of key in my_dict.keys()
:
if 'key1' in my_dict:
print("blah")
else:
print("boo")
That will be much faster as it uses the dictionary's O(1) hashing as opposed to doing an O(n) linear search on a list of keys.
in
tests for the existence of a key in a dict
:
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
Use dict.get()
to provide a default value when the key does not exist:
d = {}
for i in range(10):
d[i] = d.get(i, 0) + 1
To provide a default value for every key, either use dict.setdefault()
on each assignment:
d = {}
for i in range(10):
d[i] = d.setdefault(i, 0) + 1
or use defaultdict
from the collections
module:
from collections import defaultdict
d = defaultdict(int)
for i in range(10):
d[i] += 1