Summary: In this tutorial, we will learn 3 different ways to add new keys to an existing dictionary in Python.
There are 3 easy ways to add new key and value pairs to a Python dictionary after it has been created:
- Using
[]
- Using
.update()
- Using
|=
Let’s see an example of each of the methods.
Method 1: Using [] operator
If we assign a value to a new key by using the []
operator on the dictionary, it gets added to the dictionary.
>>> countries = {'IN': 'INDIA', 'US': 'United States of America'}
>>> print(countries)
{'IN': 'INDIA', 'US': 'United States of America'}
>>> countries['UK'] = 'United Kingdom'
>>> print(countries)
{'IN': 'INDIA', 'US': 'United States of America', 'UK': 'United Kingdom'}
Method 2: Using .update() method
We can also insert new key-value pairs by using the update()
method of the dictionary.
The update()
method accepts dictionary (or an Python iterable object with key-value pairs) and adds them to the existing dictionary object.
>>> cubes = {2: 8, 3: 27, 4: 64}
>>> print(cubes)
{2: 8, 3: 27, 4: 64}
>>> cubes.update({5: 125, 6: 216})
>>> print(cubes)
{2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
Method 3: Using |= operator [Python 3.9+]
From Python 3.9+, we can use the new update operator (|=
) to add new keys to the dictionary as follows:
>>> squares = {2: 4, 3: 9, 4: 16}
>>> print(squares)
{2: 4, 3: 9, 4: 16}
>>> squares |= {5: 25}
>>> print(squares)
{2: 4, 3: 9, 4: 16, 5: 25}
In all three ways, we can insert new keys to the dictionary. However, if the key already exists in the dictionary, its value will be updated with the new one.