How to Add to a Dictionary in Python

by | Programming, Python, Tips

The easiest way to add a new value to a dictionary is to use the subscript notation: dictionary_name[key] = value.

This tutorial will go through the various ways to add key-value pairs to a Python dictionary with code examples.


What is a Python Dictionary?

A dictionary in Python is a collection of key-value pairs. You can use a key to access the value associated with that key. A key must be immutable like a string, integer, boolean or tuple. You cannot use a mutable object like a slice, or you will raise the error: TypeError: unhashable type: ‘slice’. To define a dictionary, you must use braces {} as shown in the following example:

capital_cities = {'England':'London', 'France':'Paris', 'Italy':'Rome'}

Python Add to Dictionary Using Subscript Notation

Dictionaries are dynamic structures, and you can add or remove key-value pairs to and from a dictionary at any time. To add an item to a Python dictionary, you should assign a value to a new key in your dictionary. You cannot use the functions add(), insert() or append() as you can with a list. Let’s look at the syntax for adding a new value to a dictionary.

dictionary_name[key] = value

Let’s look at an example of adding key-value pairs to a dictionary using the subscript notation, starting with an empty dictionary.

# Define an empty dictionary

my_dict = {}

# Add key and value to my_dict using subscript notation

my_dict['England'] = 'London'

# Print the content of my_dict

print('Adding to empty dictionary: ', my_dict)

# Add another key-value pair

my_dict['Germany'] = 'Berlin'

# Print content of my_dict

print('Append to dictionary:  ', my_dict)

Let’s run the code to see what happens:

Adding to empty dictionary:  {'England': 'London'}
Append to dictionary:   {'England': 'London', 'Germany': 'Berlin'}

Python Update Dictionary

We can add key-value pairs using the dict.update() method. Let’s look at an example:

my_dict = {'England':'London', 'France':'Paris'}

dict_to_add = {'Germany':'Berlin', 'Ethiopia':'Addis Ababa'}

# Update the original dictionary with the dict_to_add content

my_dict.update(dict_to_add)

# Print new content of dictionary

print(my_dict)
{'England': 'London', 'France': 'Paris', 'Germany': 'Berlin', 'Ethiopia': 'Addis Ababa'}

You can update the original dictionary directly without defining a secondary dictionary using the following syntax:

my_dict = {'England':'London', 'France':'Paris'}

my_dict.update([('Germany','Berlin'), ('Ethiopia','Addis Ababa')])

print(my_dict)
{'England': 'London', 'France': 'Paris', 'Germany': 'Berlin', 'Ethiopia': 'Addis Ababa'}

Add an item to a dictionary using the ** operator in Python

In Python 3.5 and higher releases, you can use the unpacking operator ** to add a key-value pair to another dictionary. Applying the ** operator to a dictionary deserializes the dictionary and converts it to its key-value pairs. Let’s look at an example of the unpacking operator to merge two dictionaries.

my_dict = {'England':'London', 'France':'Paris'}

print('Original Dictionary is: ', my_dict)

dict_to_add = {'Japan':'Tokyo', 'Russia':'Moscow'}

my_dict = {**my_dict, **dict_to_add}

print('Modified dictionary is: ', my_dict)

The above code defines two dictionaries and uses the unpacking operator to merge the second to the first. Let’s run the code to see the result:

Original Dictionary is:  {'England': 'London', 'France': 'Paris'}

Modified dictionary is:  {'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo', 'Russia': 'Moscow'}

For further reading on unpacking iterable objects like dictionaries, go to the article: How to Solve Python TypeError: cannot unpack non-iterable NoneType object.

Using list and dict.items() to add key-value pairs to a dictionary

We can add key-value pairs to a dictionary using the items() method, which returns a view object. The view object contains the key-value pairs of the dictionary as tuples in a list. Let’s look at an example of using dict.items() to add the key-value pairs of one dictionary to another.

my_dict = {'England':'London', 'France':'Paris'}

print('Original Dictionary is: ', my_dict)

dict_to_add = {'Japan':'Tokyo', 'Russia':'Moscow'}

my_dict = dict(list(my_dict.items()) + list(dict_to_add.items()))

print('Modified dictionary is: ', my_dict)

The above program obtains lists of key-value tuple pairs for the two dictionaries and combines them using the concatenation operator. The program converts the combination to a dictionary using dict() and prints the modified dictionary to the console. Let’s run the code to see the result:

Original Dictionary is:  {'England': 'London', 'France': 'Paris'}
Modified dictionary is:  {'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo', 'Russia': 'Moscow'}

Use List Comprehension to Combine Dictionary Key-Value Pairs

We can use list comprehension to create a dictionary based on the values from two or more dictionaries. We can use the items() method mentioned above to get the key-value pairs of the dictionaries. Let’s look at an example of using list comprehension to combine two dictionaries and add them to a new dictionary.

my_dict = {'England':'London', 'France':'Paris'}

print('First Dictionary is: ', my_dict)

my_dict2 = {'Japan':'Tokyo', 'Russia':'Moscow'}

print('Second Dictionary is: ', my_dict2)

new_dict = {}

new_dict = dict(i for d in [my_dict,my_dict2] for i in d.items() )

print(new_dict)

The above program defines three dictionaries, two with key-value pairs and an empty dictionary to store the combined values. The program uses list comprehension to iterate over both dictionaries and add the key-value pairs to the third dictionary using the items() method. Let’s run the code to see the result:

First Dictionary is:  {'England': 'London', 'France': 'Paris'}
Second Dictionary is:  {'Japan': 'Tokyo', 'Russia': 'Moscow'}
{'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo', 'Russia': 'Moscow'}

Using the __setitem__() Method to Add Key-Value pairs to a Dictionary

We can use the built-in __setitem__() method to add key-value pairs to a dictionary. Let’s look at an example:

my_dict = {'England':'London', 'France':'Paris'}

print('Original dictionary: ', my_dict)

my_dict.__setitem__('Japan', 'Tokyo')

print('Modified dictionary: ', my_dict)

The above code adds a key-value tuple to the dictionary using the __setitem__() method. Let’s run the program to see the result:

Original dictionary:  {'England': 'London', 'France': 'Paris'}
Modified dictionary:  {'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo'}

Use dict.setdefault() to add Key-Value pairs to Dictionary

We can use the dict.setdefault() to add to a dictionary. The syntax is

setdefault(key[,default])

If the key is in the dictionary, the function will return its value. If not, it will insert the key with a value of default and return default. The default of default is None. Let’s look at an example of adding a key-value pair to an existing dictionary.

my_dict = {'England':'London', 'France':'Paris'}

print('Original Dictionary is: ', my_dict)

my_dict.setdefault('Japan','Tokyo')

print(my_dict)

The key we want to add is Japan, which does not exist in my_dict, so setdefault() will insert this key and the corresponding value. Let’s run the code to see what happens:

Original Dictionary is:  {'England': 'London', 'France': 'Paris'}
{'England': 'London', 'France': 'Paris', 'Japan': 'Tokyo'}

Summary

Congratulations on reading to the end of this tutorial! You have seen different ways to add an item to a dictionary in Python. Now you can add dictionaries like a pro!

For further reading on dictionaries, go to the articles:

To learn more about Python, specific to data science and machine learning, go to the online courses page for Python.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee