Nested Dictionary in Python | Create, Example

As we have known earlier, the ordered collection of elements is known as a dictionary. It contains various items in the form of key-value pairs inside the curly braces ({ }).

The general syntax to create a dictionary in Python is as:

dict_name = {'key1' : 'value1', 'key2' : 'value2', 'key3' : 'value3' }

In Python, a dictionary can also contain many dictionaries. When we put a dictionary inside another dictionary, then it is called nested dictionary in Python.

In other words, a nested dictionary is the process of storing multiple dictionaries inside a dictionary.

In the real world of technology, a nested dictionary is useful when we are processing and transforming data from one format into the other.

A simple example of dictionaries inside a dictionary is shown in the below code.

nested_dcit = {
        'dict1' : {'key1' : 'value1'},
        'dict2' : {'key2' : 'value2'},
        'dict3' : {'key3' : 'value3'}
}

In this example, the nested_dict is the name of a nested dictionary that contains three dictionaries named dict1, dict2, and dict3. These are separate dictionaries that contain their key-value pairs.

How to create Nested Dictionary in Python?


We can create or define a nested dictionary by putting comma-separated dictionaries within curly braces. The general syntax to create a nested dictionary in Python is as:

dict_name = {
    "nested_dict1" : {key: value, key: value},
    "nested_dict2" : {key: value, key: value},
    "nested_dict3" : {key: value, key: value}
}

Here, each individual dictionary begins with a name of nested dictionary separated by a pair of curly brackets ({ }).

Let’s take some valid examples of creating or defining nested dictionaries in Python.

Example 1:

gradebook = {
     "Mahika" : {
         "Maths" : "A", 
         "Science" : "A++",
         "English" : "A",
         "GDP" : 9.8
     },
     "Ivaan" : {
        "Maths" : "A",
        "Science" : "A",
        "English" : "B",
        "GDP" : 9.3
     },
    "Mark" : {
       "Maths" : "B",
       "Science" : "C", 
       "English" : "A",
       "GDP" : 8.5
    }
}

In this example, gradebook is the name of nested dictionary with the dictionary Mahika, Ivaan, and Mark. Dictionaries Mahika, Ivaan, and Mark are separate dictionaries that contain their key-value pairs. So, we can say that nested dictionary is a collection of dictionaries into a single dictionary.

Example 2:

nest_dict = {
   'dict1' : {'A' : {dictA}, 'B' : {dictB}},
   'dict2' : [list1],
   'dict3' : {'X' : val1, 'Y' : val2, 'Z' : val3}
}

In this example, we have created a nested dictionary with a mixed of dictionary objects and a list object inside it. The nested dictionary contains three dictionaries named dict1, dict2, and dict3.

The dictionary dict1 has further dictionaries named A and B inside it. The dict3 is a regular dictionary with key-value pairs as entries, as in the above code.

Another way to Create a Nested Dictionary


Another way to create a nested dictionary in Python is by using the inbuilt dict() method provided by Python. To create it, simply pass dictionary elements (as key-value pairs) as keyword arguments to dict() method.


The basic form to create a nested dictionary is as follows:

# Creating a nested dictionary named my_dict by using dict() method.
my_dict = dict(st1 = {'name': 'Amit', 'age': '15'},
               st2 = {'name': 'Mark', 'age': '16'})
print(my_dict)
Output:
       {'st1': {'name': 'Amit', 'age': '15'}, 'st2': {'name': 'Mark', 'age': '16'}}

Access Elements of Nested Dictionaries


To access an element of a nested dictionary in Python, we use indexing [] syntax. We write the dictionary name and then surround the key in square brackets. Let’s take some example program based on accessing elements of a nested dictionary.

Example 3:

# Python program to access elements of a nested dictionary.
# Creating a nested dictionary named emp.
emp = {
    'dict1' : {'name': 'Amit', 'age': 28, 'post': 'Sr Developer'},
    'dict2' : {'name': 'Mark', 'age': 34, 'post': 'Manager'},
    'dict3' : {'name': 'John', 'age': 32, 'post': 'HR'}
}
# Displaying a complete nested dictionary.
print("Nested dictionary: ")
print(emp)

# Accessing the key-value pairs of dict1 dictionary.
print("\nDictionary 1: ")
print(emp['dict1'])

# Accessing each value of dict1 keys.
print("Name: ", emp['dict1']['name'])
print("Age:", emp['dict1']['age'])
print("Post: ", emp['dict1']['post'])

# Similarly, accessing the key-value pairs of dict2 dictionary.
print("\nDictionary 2: ")
print(emp['dict2'])

# Accessing each value of dict2 keys.
print("Name: ", emp['dict2']['name'])
print("Age:", emp['dict2']['age'])
print("Post: ", emp['dict2']['post'])
Output:
      Nested dictionary: 
      {'dict1': {'name': 'Amit', 'age': 28, 'post': 'Sr Developer'}, 
       'dict2': {'name': 'Mark', 'age': 34, 'post': 'Manager'}, 
       'dict3': {'name': 'John', 'age': 32, 'post': 'HR'}}

      Dictionary 1: 
      {'name': 'Amit', 'age': 28, 'post': 'Sr Developer'}
      Name:  Amit
      Age: 28
      Post:  Sr Developer

      Dictionary 2: 
      {'name': 'Mark', 'age': 34, 'post': 'Manager'}
      Name:  Mark
      Age: 34
      Post:  Manager

In this example, we have created a nested dictionary that contains three more dictionaries, named dict1, dict2, and dict3. Each dictionary has regular key-value pairs with name, age, and post as its entries. Then, we have accessed a nested dictionary and sub dictionaries using indexing [ ] syntax.

Another way to Access Nested Dictionary


Another way to access elements of a nested dictionary in Python is by using the built-in get() method. Let’s take an example in which we will access elements of a nested dictionary by using get() method.


Example 4:

# Python program to access elements of a nested dictionary.
# Creating a nested dictionary named st.
st = {
    1: {'name': 'Amit', 'std': '8th'},
    2: {'name': 'Mark', 'std': '6th'},
    3: {'name': 'John', 'std': '7th'}
}
# Displaying a complete nested dictionary.
print("Nested dictionary: ")
print(st)

# Accessing the key-value pairs of dictionary 1.
print("\nDictionary 1: ")
print(st.get(1))
print("Name: ", st.get(1).get('name'))
print("Std:", st.get(1).get('std'))


# Similarly, accessing the key-value pairs of dictionary 2.
print("\nDictionary 2: ")
print(st.get(2))
print("Name: ", st.get(2).get('name'))
print("Age:", st.get(2).get('std'))

# Accessing the key-value pairs of dictionary 3.
print("\nDictionary 3: ")
print(st.get(3))
print("Name: ", st.get(3).get('name'))
print("Age:", st.get(3).get('std'))
Output:
      Nested dictionary: 
      {1: {'name': 'Amit', 'std': '8th'}, 2: {'name': 'Mark', 'std': '6th'}, 3: {'name': 'John', 'std': '7th'}}

      Dictionary 1: 
      {'name': 'Amit', 'std': '8th'}
      Name:  Amit
      Std: 8th

      Dictionary 2: 
      {'name': 'Mark', 'std': '6th'}
      Name:  Mark
      Age: 6th

      Dictionary 3: 
      {'name': 'John', 'std': '7th'}
      Name:  John
      Age: 7th

Remember that if the key is not present in the dictionary, then the indexing [ ] syntax will generate an exception named KeyError.

Example 5:

# Creating a nested dictionary named st having two dictionaries.
st = {
    1: {'name': 'Amit', 'std': '8th'},
    2: {'name': 'Mark', 'std': '6th'},
}
# Accessing a key-value pair of dictionary 1 which is not present in the dictionary 1.
print("Name: ", st[1]['age'])
Output:
      KeyError: 'age'

To avoid such exception, you can use the get() method provided by the dictionary. This method returns the value of key if key is present in the dictionary. Otherwise, it returns None. It never raises a KeyError that’s the difference between using get() method and indexing [ ] syntax.

Adding a Dictionary to Nested Dictionary


It is very simple to add a sub dictionary to a nested dictionary in Python. Simply write the dictionary name, surround the sub dictionary name in square brackets, and then assign its key-value pairs. The general syntax to add elements of a nested dictionary is as:

dictionary_name[key] = value

Example 6:

# Python program to add a sub dictionary to a nested dictionary.
# Creating a nested dictionary.
my_dict = {'emp1': {'name': 'John', 'age': 25},
           'emp2': {'name': 'Mark', 'age': 23}
           }
print('Nested dictionary before adding: ')
print(my_dict)

# Adding a sub dictionary to a nested dictionary.
my_dict['emp3'] = {'name': 'Bob', 'age': 22}

print("Nested dictionary after adding: ")
print(my_dict)
Output:
      Nested dictionary before adding: 
      {'emp1': {'name': 'John', 'age': 25}, 'emp2': {'name': 'Mark', 'age': 23}}
      Nested dictionary after adding: 
      {'emp1': {'name': 'John', 'age': 25}, 'emp2': {'name': 'Mark', 'age': 23}, 'emp3': {'name': 'Bob', 'age': 22}}

If a sub dictionary is already present in the nested dictionary, then Python will replace only its new key-value pairs.

Example 7:

my_dict = {'emp1': {'name': 'John', 'age': 25},
           'emp2': {'name': 'Mark', 'age': 23}
           }
print('Nested dictionary before adding: ')
print(my_dict)

# Adding a sub dictionary which is already present in the nested dictionary.
my_dict['emp3'] = {'name': 'Priya', 'age': 26}

print("Nested dictionary after adding: ")
print(my_dict)
Output:
      Nested dictionary before adding: 
      {'emp1': {'name': 'John', 'age': 25}, 'emp2': {'name': 'Mark', 'age': 23}}
      Nested dictionary after adding: 
      {'emp1': {'name': 'John', 'age': 25}, 'emp2': {'name': 'Mark', 'age': 23}, 'emp3': {'name': 'Priya', 'age': 26}}

Updating Nested Dictionary Elements


We can easily update nested dictionary elements. Simply write the dictionary name, surround the key in square brackets, and then assign a new value. The general syntax to update nested dictionary element in Python is as:

dictionary_name[key] = value

If the key is already present in the dictionary, then the value of that key will be replaced by a new one. If we entered the key which is not present in the dictionary, then it will add that key with respective value. Following example updates the value of dict1 dictionary inside st dictionary.

Example 8:

# Python program to update nested dictionary elements.
st = {'st1': {'name': 'John', 'scName': 'RSVM'},
      'st2': {'name': 'Mark', 'scName': 'DPS'}
}
# Displaying dictionary elements before update.
print('Nested dictionary before updating: ')
print(st)

# Updating the value of st2.
st['st2'] = {'name' : 'Deep', 'scName' : 'DAV'}

# Displaying the dictionary elements after updating.
print('Nested dictionary elements after updating values: ')
print(st)
Output:
      Nested dictionary before updating: 
      {'st1': {'name': 'John', 'scName': 'RSVM'}, 'st2': {'name': 'Mark', 'scName': 'DPS'}}
      Nested dictionary elements after updating values: 
      {'st1': {'name': 'John', 'scName': 'RSVM'}, 'st2': {'name': 'Deep', 'scName': 'DAV'}}

Example 9:

# Python program to update a specific element of nested dictionary.
st = {'st1': {'name': 'Tripti', 'scName': 'RSVM'},
      'st2': {'name': 'Saanvi', 'scName': 'DPS'}
}
# Displaying dictionary elements before update.
print('Nested dictionary before updating: ')
print(st)

# Updating the value of key scName inside st2 dictionary.
st['st2']['scName'] = 'DAV'

# Displaying the dictionary elements after updating.
print('Nested dictionary elements after updating values: ')
print(st)
Output:
      Nested dictionary before updating: 
      {'st1': {'name': 'Tripti', 'scName': 'RSVM'}, 'st2': {'name': 'Saanvi', 'scName': 'DPS'}}
      Nested dictionary elements after updating values: 
      {'st1': {'name': 'Tripti', 'scName': 'RSVM'}, 'st2': {'name': 'Saanvi', 'scName': 'DAV'}}

Deleting Elements from Nested Dictionary


There are two ways to delete or remove elements from a nested dictionary in Python programming language. They are:

(1) Using del keyword:

We can use del keyword to remove the key which is present in the dictionary. The basic form to delete a key-value pair from the dictionary is as:

del dictionary_name[key]

Example 10:

# Python program to delete a specific element of nested dictionary.
teacher = {
    't1' : {'name' : 'Tripti', 'salary' : 25000},
    't2' : {'name' : 'Radha', 'salary' : 26000},
    't3' : {'name' : 'Kusum', 'salary' : 23000}
}
# Displaying dictionary elements before remove.
print("Nested dictionary before delete: ")
print(teacher)

# Deleting a key from a dictionary using del keyword.
del teacher['t3']

# Displaying dictionary elements after delete.
print('Nested dictionary after delete: ')
print(teacher)
Output:
      Nested dictionary before delete: 
      {'t1': {'name': 'Tripti', 'salary': 25000}, 't2': {'name': 'Radha', 'salary': 26000}, 't3': {'name': 'Kusum', 'salary': 23000}}
      Nested dictionary after delete: 
      {'t1': {'name': 'Tripti', 'salary': 25000}, 't2': {'name': 'Radha', 'salary': 26000}}

Example 11:

# Python program to delete a specific element of nested dictionary.
teacher = {
    't1' : {'name' : 'Kusum', 'salary' : 25000},
    't2' : {'name' : 'Mohan', 'salary' : 26000},
}
# Displaying dictionary elements before remove.
print("Nested dictionary before delete: ")
print(teacher)

# Deleting a key from a sub dictionary using del keyword.
del teacher['t2']['salary']

# Displaying dictionary elements after delete.
print('Nested dictionary after delete: ')
print(teacher)
Output:
      Nested dictionary before delete: 
      {'t1': {'name': 'Kusum', 'salary': 25000}, 't2': {'name': 'Mohan', 'salary': 26000}}
      Nested dictionary after delete: 
      {'t1': {'name': 'Kusum', 'salary': 25000}, 't2': {'name': 'Mohan'}}

The major drawback of using del keyword is that if you want to delete a key that does not exist in the dictionary, then it will generate an exception error named KeyError.

(2) Using pop() method:

This method deletes a key with respective value from the dictionary. The general syntax to use this method is as:

dictionary_name.pop(key)

Example 12:

teacher = {
    't1' : {'name' : 'Mark', 'Subject' : 'Chemistry'},
    't2' : {'name' : 'Harry', 'Subject' : 'Physics'},
}
# Displaying dictionary elements before remove.
print("Nested dictionary before delete: ")
print(teacher)

# Deleting a key from a sub dictionary using pop() method.
teacher.pop('t2')

# Displaying dictionary elements after delete.
print('Nested dictionary after delete: ')
print(teacher)
Output:
       Nested dictionary before delete: 
       {'t1': {'name': 'Mark', 'Subject': 'Chemistry'}, 't2': {'name': 'Harry', 'Subject': 'Physics'}}
       Nested dictionary after delete: 
       {'t1': {'name': 'Mark', 'Subject': 'Chemistry'}}

How to Merge Two Nested Dictionaries in Python


Python language provides a built-in method named update() to merge the keys and values of one nested dictionary into another. Remember that this method blindly overwrites values of the same key if there’s a collision.

Example 13:

# Python program to merge nested dictionaries.
D1 = {'teacher1': {'name': 'Bob', 'subject': 'physics'},
      'teacher2': {'name': 'Kim', 'subject': 'maths'}}

D2 = {'teacher3': {'name': 'Sam', 'subject': 'chemistry'},
      'teacher4': {'name': 'Max', 'subject': 'biology'}}

# Merging dictionary 2 into dictionary 1.
D1.update(D2)

# Displaying a dictionary after merging.
print(D1)
Output:
       {'teacher1': {'name': 'Bob', 'subject': 'physics'}, 'teacher2': {'name': 'Kim', 'subject': 'maths'}, 
        'teacher3': {'name': 'Sam', 'subject': 'chemistry'}, 'teacher4': {'name': 'Max', 'subject': 'biology'}}

Iterate over a Nested Dictionary


We can easily iterate over all element values in a nested dictionary using nested for loop. Look at the below example code where we have iterated over elements of a nested dictionary.

Example 14:

# Python program to iterate over elements of nested dictionaries.
D1 = {'teacher1': {'name': 'Bob', 'subject': 'physics'},
      'teacher2': {'name': 'Kim', 'subject': 'maths'},
      'teacher3': {'name': 'Sam', 'subject': 'chemistry'}
}
# Iterating over elements of a nested dictionary.
for t1 in D1:
    print(t1)

# Iterating over keys of nested dictionaries.
for t1, info in D1.items():
    print(t1, info)
Output:
      teacher1
      teacher2
      teacher3
      teacher1 {'name': 'Bob', 'subject': 'physics'}
      teacher2 {'name': 'Kim', 'subject': 'maths'}
      teacher3 {'name': 'Sam', 'subject': 'chemistry'}

In this tutorial, we have discussed nested dictionaries in Python with lots of important examples. Hope that you will have understood the basic points of nested dictionary and practiced all example programs discussed above.
Thanks for reading!!!

Please share your love