You can create a nested dictionary in Python by placing comma-separated dictionaries within curly braces {}.

A Python nested dictionary allows you to store and access data using the key-value mapping structure within an existing dictionary.

This tutorial will go through creating and modifying a nested dictionary with examples.


What is a Dictionary in Python?

A Python dictionary is a built-in Python container that stores elements as a key-value pair. As of Python version 3.7, a dictionary is an ordered collection that is mutable and does not allow duplicates. For versions before 3.7, dictionaries are unordered. We can write dictionaries using curly brackets to contain the key-value pairs. Let’s look at an example of a dictionary to store the characteristics of the electron particle:

electron_dict = {
"mass":0.51,
"charge": -1,
"spin": 1/2,
}
print(electron_dict)
{'mass': 0.51, 'charge': -1, 'spin': 0.5}

The left-hand side of the colon is the key, and the right-hand side is the value. A single key-value pair is a dictionary item, and we can refer to a dictionary item using the key name.

Creating a Nested Dictionary in Python

A Python nested dictionary is a collection of dictionaries inside a single dictionary. You can nest as many dictionaries in a dictionary as you want. Let’s use a nested dictionary to store dictionaries for types of pizza. Each dictionary will have the following keys:

  • Pizza name
  • Price per slice
  • Number of slices
pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

print(pizza_types)

Here, pizza_types is a nested dictionary with dictionaries 0, 1, 2. Each dictionary has its key-value pairs. Using a nested dictionary allows us to store dictionaries describing the same information. If we did not use a nested dictionary, we would have to store each dictionary in separate variables.

Let’s run the code to get the output:

{0: {'pizza_name': 'margherita', 'price_per_slice': 1.0, 'slices': 12}, 1: {'pizza_name': 'pepperoni', 'price_per_slice': 1.5, 'slices': 9}, 2: {'pizza_name': 'four cheeses', 'price_per_slice': 2.5, 'slices': 15}}

Accessing Items in a Nested Dictionary in Python

To access elements of a nested dictionary, we need to use the indexing syntax []. The integer we put in the first set of square brackets tells Python which dictionary to access, then we specify a key in the second set of square brackets to get the specific value we want from the specified dictionary. Let’s retrieve the information about the Margherita pizza from the pizza_types dictionary:

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

print(pizza_types[0]['pizza_name'])

print(pizza_types[0]['price_per_slice'])

print(pizza_types[0]['slices'])

In the above program, we print the value of the keys pizza_name, price_per_slice, and slices from the internal dictionary 0. Let’s run the code to get the result:

margherita
1.0
12

Updating a Nested Dictionary in Python: Add Element

To add an element to a nested dictionary, we can use the subscript notation. The syntax for adding an element to a dictionary is:

dictionary_name[new_key] = new_value

Let’s look at an example of updating one of the nested dictionaries in pizza_types to include whether the pizza is vegetarian or not.

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

pizza_types[0]["vegetarian"]=True

print(pizza_types[0])

The key “vegetarian” stores a boolean value. Let’s run the code to get the result:

{'pizza_name': 'margherita', 'price_per_slice': 1.0, 'slices': 12, 'vegetarian': True}

Updating a Nested Dictionary in Python: Add Dictionary

We can add another nested dictionary by creating an empty dictionary and assigning it to the large dictionary with an index number one greater than the total number of nested dictionaries. We then need to fill the new dictionary with the relevant key-value pairs. Let’s look at an example of adding a dictionary for a new pizza to the pizza_types dictionary.

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

pizza_types[3] = {}

pizza_types[3]['pizza_name'] = 'ham and pineapple'

pizza_types[3]['price_per_slice'] = 3.00

pizza_types[3]['slices'] = 20

print(pizza_types)

We create an empty dictionary 3 inside the dictionary pizza_type in the above program. Then, we add the key-value pairs for pizza_name, price_per_slice, and slices. Let’s run the code to validate the contents of the updated dictionary:

{0: {'pizza_name': 'margherita', 'price_per_slice': 1.0, 'slices': 12}, 1: {'pizza_name': 'pepperoni', 'price_per_slice': 1.5, 'slices': 9}, 2: {'pizza_name': 'four cheeses', 'price_per_slice': 2.5, 'slices': 15}, 3: {'pizza_name': 'ham and pineapple', 'price_per_slice': 3.0, 'slices': 20}}

You can also assign a dictionary literal to pizza_types[3], for example:

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

pizza_types[3] = {'pizza_name':'ham and pineapple', 'price_per_slice':'3.00', 'slices':20}

print(pizza_types)

We assign a dictionary literal to pizza_types[3]. The literal has the keys pizza_name, price_per_slice, and slices with their respective values. Let’s run the code to validate the contents of the updated dictionary:

{0: {'pizza_name': 'margherita', 'price_per_slice': 1.0, 'slices': 12}, 1: {'pizza_name': 'pepperoni', 'price_per_slice': 1.5, 'slices': 9}, 2: {'pizza_name': 'four cheeses', 'price_per_slice': 2.5, 'slices': 15}, 3: {'pizza_name': 'ham and pineapple', 'price_per_slice': '3.00', 'slices': 20}}

Deleting an Element in a Nested Dictionary in Python

We can use the del statement to delete an item in a dictionary. Let’s look at an example where we no longer want to show the number of slices available for the different pizzas in the pizza_types dictionary. We can use del to delete the key-value pairs of slices from the nested dictionaries as follows:

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

del pizza_types[0]['slices']

del pizza_types[1]['slices']

del pizza_types[2]['slices']

print(pizza_types)

Let’s run the code to get the result:

{0: {'pizza_name': 'margherita', 'price_per_slice': 1.0}, 1: {'pizza_name': 'pepperoni', 'price_per_slice': 1.5}, 2: {'pizza_name': 'four cheeses', 'price_per_slice': 2.5}}

We successfully deleted the key-value pairs for slices from the internal dictionaries.

Deleting a Nested Dictionary in Python

We can use the del statement to delete dictionaries. Let’s look at an example where we delete the pepperoni pizza from our pizza_types dictionary. We can use del to delete the pepperoni pizza nested dictionary as follows:

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

del pizza_types[1]

print(pizza_types)

In the above program, we used the del statement to delete the value in the nested dictionary with a key equal to 1. This operation removes the pepperoni dictionary from the nested dictionary. The program returns:

{0: {'pizza_name': 'margherita', 'price_per_slice': 1.0, 'slices': 12}, 2: {'pizza_name': 'four cheeses', 'price_per_slice': 2.5, 'slices': 15}}

Iterating Over a Nested Dictionary in Python

To iterate over a nested dictionary, we can use for loops. Let’s look at an example where we iterate over the pizza_types dictionary and get the contents of each internal dictionary:

pizza_types = { 0: {'pizza_name': 'margherita', 'price_per_slice': 1.00, 'slices': 12},
                      1: {'pizza_name': 'pepperoni', 'price_per_slice':1.50, 'slices': 9},
                      2: {'pizza_name': 'four cheeses', 
'price_per_slice':2.50, 'slices':15}}

for pizza_id, pizza_info in pizza_types.items():
    print('\nPizza ID: ', pizza_id)

    for key in pizza_info:
        print(key + ':', pizza_info[key])

In the above program, the first loop goes through each key and value in the pizza_types nested dictionary. We use the items() method to generate a view object containing a list of all the keys and values in the pizza_types dictionary. The for loop iterates over the key-value list and returns all the keys in the nested dictionary, which are the Pizza IDs. The second loop uses the in operator to go through the keys pizza_name, price_per_slice, and slices of each pizza. Then, the loop prints the key of the pizza information and the value for that key to the console. Let’s run the code to get the output:

Pizza ID:  0
pizza_name: margherita
price_per_slice: 1.0
slices: 12

Pizza ID:  1
pizza_name: pepperoni
price_per_slice: 1.5
slices: 9

Pizza ID:  2
pizza_name: four cheeses
price_per_slice: 2.5
slices: 15

Summary

Congratulations on reading to the end of this article! You have gone through creating and manipulating a nested dictionary in Python. Here are some key points to remember about nested dictionaries:

  • Nested dictionaries have key-value structure just like dictionaries
  • You can access internal dictionaries by key
  • You can add to or delete from a nested dictionary as needed
  • A nested dictionary are unordered collections of dictionaries

For further reading on dictionaries, go to the articles: 

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!