Add new keys to a dictionary?


Question

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.

1
2338
5/3/2019 10:04:56 AM

Accepted Answer

d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
3073
1/4/2019 1:44:21 PM

To add multiple keys simultaneously:

>>> x = {1:2}
>>> print x
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print x
{1: 2, 3: 4, 5: 6, 7: 8}

For adding a single key, the accepted answer has less computational overhead.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon