Introduction
A dictionary in Python is a collection of items that store data as key-value pairs. We can access and manipulate dictionary items based on their key. Dictionaries are mutable and allow us to add new items to them.
The quickest way to add a single item to a dictionary is by using a dictionary's index with a new key and assigning a value. For example, we add a new key-value pair like this:
snacks['chocolate'] = 5
Python allows adding multiple items to dictionaries as well. In this tutorial, we'll take a look at how to add keys to a dictionary in Python.
Add Key to a Python Dictionary
There are multiple ways to add a new key-value pair to an existing dictionary. Let's have a look at a few common ways to do so.
Add Key with Value
We can add a new key to a dictionary by assigning a value to it. If the key is already present, it overwrites the value it points to. The key has to be written in subscript notation to the dictionary like this:
my_dictionary[new_key] = new_value
This key-value pair will be added to the dictionary. If you're using Python 3.6 or later, it will be added as the last item of the dictionary.
Let's make a dictionary, and then add a new key-value pair with this approach:
squares = {1: 1, 2: 4, 3: 9}
squares[4] = 16 # Adding new key-value pair
print(squares)
This will result in:
{1: 1, 2: 4, 3: 9, 4: 16}
Add Key to Dictionary without Value
If you'd just like to add a key, without a value, you can simply put None
instead of the value, with any of the methods covered in this article:
squares = {1: 1, 2: 4, 3: 9}
squares['x'] = None # Adding new key without value
print(squares)
This results in:
{1: 1, 2: 4, 3: 9, 'x': None}
Add Multiple Key-Value Pairs with update()
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update()
method. This method takes an argument of type dict
or any iterable that has the length of two - like ((key1, value1),)
, and updates the dictionary with new key-value pairs.
If the key is already present in the dictionary, it gets overwritten with the new value.
The keys can also be passed as keyword arguments to this method with their corresponding values, like dictionary.update(new_key=new_value)
.
Note: This is arguably the most popular method of adding new keys and values to a dictionary.
Let's use the update()
method to add multiple key-value pairs to a dictionary:
rainbow = {'red': 1}
# Update by passing dictionary
new_key_values_dict = {'orange': 2, 'yellow': 3}
rainbow.update(new_key_values_dict)
print("update by passing dictionary")
print(rainbow)
# Update by passing iterables
new_key_values_itr = (('green',4), ('blue',5))
rainbow.update(new_key_values_itr)
print("update by passing iterables")
print(rainbow)
# Update using keyword arguments
rainbow.update(indigo=6, violet=7)
print("update using keyword arguments")
print(rainbow)
Running this code will produce the following output:
update by passing dictionary
{'red': 1, 'orange': 2, 'yellow': 3}
update by passing iterables
{'red': 1, 'orange': 2, 'yellow': 3, 'green': 4, 'blue': 5}
update using keyword arguments
{'red': 1, 'orange': 2, 'yellow': 3, 'green': 4, 'blue': 5, 'indigo': 6, 'violet': 7}
Using Merge Operator (Python 3.9+)
From Python version 3.9, Merge (|
) and Update (|=
) operators have been added to the built-in dict
class.
These are very convenient methods to add multiple key-value pairs to a dictionary. The Merge (|
) operator creates a new dictionary with the keys and values of both of the given dictionaries. We can then assign this result to a new dictionary.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Whereas the Update (|=
) operator, adds the key-value pairs of the second dictionary into the first dictionary. So, the existing dictionary gets updated with multiple key-value pairs from another dictionary.
Here's an example of using Merge (|
) and Update (|=
) operators to add new keys to a dictionary:
colors_set1 = {‘red’: 1, 'orange’: 2, 'yellow': 3}
colors_set2 = {'green': 4, 'blue': 5, 'indigo': 6, 'violet': 7}
# Merge operator
rainbow = colors_set1 | colors_set2
print("using merge:", rainbow)
# Update operator
colors_set1 |= colors_set2
print("using update:", colors_set1)
This code will produce the following output on the Python(3.9+) interpreter:
using merge: {'red': 1, 'orange': 2, 'yellow': 3, 'green': 4, 'blue': 5, 'indigo': 6, 'violet': 7}
using update: {'red': 1, 'orange': 2, 'yellow': 3, 'green': 4, 'blue': 5, 'indigo': 6, 'violet': 7}
Conclusion
In this tutorial, we learned how we can add a new key to a dictionary. We first added the key-value pair using subscript notation - we added a key to a dictionary by assigning a value to it. We then looked at the update()
method to add multiple key-value pairs to a dictionary. We've also used the update()
method with parameters of type dictionary, tuple, and keyword arguments. Lastly, we probed into the Merge and Update operators available from Python versions 3.9 onwards.
The update()
method of dictionary proves to be the most popular way to add new keys to an existing dictionary.