Is it possible to add a key to a Python dictionary after it has been created?
It doesn\'t seem to have an .add()
method.
I think it would also be useful to point out Python's collections module that consists of many useful dictionary subclasses and wrappers that simplify the addition and modification of data types in a dictionary, specifically defaultdict:
dict subclass that calls a factory function to supply missing values
This is particularly useful if you are working with dictionaries that always consist of the same data types or structures, for example a dictionary of lists.
>>> from collections import defaultdict
>>> example = defaultdict(int)
>>> example['key'] += 1
>>> example['key']
defaultdict(, {'key': 1})
If the key does not yet exist, defaultdict
assigns the value given (in our case 10
) as the initial value to the dictionary (often used inside loops). This operation therefore does two things: it adds a new key to a dictionary (as per question), and assigns the value if the key doesn't yet exist. With the standard dictionary, this would have raised an error as the +=
operation is trying to access a value that doesn't yet exist:
>>> example = dict()
>>> example['key'] += 1
Traceback (most recent call last):
File "", line 1, in
KeyError: 'key'
Without the use of defaultdict
, the amount of code to add a new element would be much greater and perhaps looks something like:
# This type of code would often be inside a loop
if 'key' not in example:
example['key'] = 0 # add key and initial value to dict; could also be a list
example['key'] += 1 # this is implementing a counter
defaultdict
can also be used with complex data types such as list
and set
:
>>> example = defaultdict(list)
>>> example['key'].append(1)
>>> example
defaultdict(, {'key': [1]})
Adding an element automatically initialises the list.