How Can I Add New Keys to a Dictionary?
How Do I Add a Key to an Existing Dictionary? It Doesn't Have An. Add() Method. 4 18 Answers You Create a New Key/Value Pair on a Dictionary by Assigning a...
How do I add a key to an existing dictionary? It doesn't have an .add() method.
18 Answers
You create a new key/value pair on a dictionary by assigning a value to that key
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
To add multiple keys simultaneously, use dict.update():
>>> 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.
I feel like consolidating info about Python dictionaries:
Must Read
Creating an empty dictionary
data = {}
# OR
data = dict()