Skip to main content

Python Nested Dictionary

In this chapter we will discuss Nested Dictionary in Python.

A Python Dictionary is an unordered collection of items.

Main points to remember about Python dictionaries:

  1. Nested dictionary is an unordered collection of dictionary
  2. Slicing Nested Dictionary isn't possible.
  3. You can shrink or grow nested dictionary as needed.
  4. Dictionary has key and value.
  5. Dictionary are accessed using key.
note

See Python Dictionary to learn more about dictionaries.

What is Nested Dictionary?

A nested dictionary is a collection of dictionaries into one single dictionary.

nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}

Create a Nested Dictionary

A nested dictionary is created in the same way that a normal dictionary is created: the only difference is that each value is another dictionary.

For example, create a nested dictionary students that contains two other dictionaries 1 and 2 where each represents a student with name, age and gender.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}
print(students)

Output:

{1: {'name': 'Tom', 'age': '23', 'gender': 'Male'}, 2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

Equivalently, you can use the constructor dict()

students = dict(1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'})
print(students)

Output:

{1: {'name': 'Tom', 'age': '23', 'gender': 'Male'}, 2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

Access elements of a Nested Dictionary

Individual elements of a nested dictionary can be accessed by specifying the key between multiple square brackets.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

print(students[1]['name']) # Tom
print(students[1]['age']) # 23
print(students[1]['gender']) # Male
warning

An exception is raised if you reference a key that is not in the nested dictionary.

print(students[1]['height'])
# KeyError: 'height'

The get() method of the dictionary returns the value of the key if the key is in the dictionary, otherwise None. This prevents a KeyError from being raised.

# key present
print(students[1].get('name')) # Tom

# key absent
print(students[1].get('height')) # None

Nested Dictionary Manipulation

Add and Update elements to a Nested Dictionary

To add or update elements to a nested dictionary, simply reference the element with its key and assign a value.

If the key is new, it is added to the dictionary with its value.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

students[3] = {'name': 'Ryan', 'age': '27', 'gender': 'Male'}

print(students)
{1: {'name': 'Thomas', 'age': '24', 'gender': 'Male'}, 2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}, 3: {'name': 'Ryan', 'age': '27', 'gender': 'Male'}}

If the key is already in the dictionary, its value is replaced by the new one.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

students[1] = {'name': 'Thomas', 'age': '24', 'gender': 'Male'}

print(students)
{1: {'name': 'Thomas', 'age': '24', 'gender': 'Male'}, 2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

Delete elements from a Nested Dictionary

There are several ways to remove items from a nested dictionary.

Remove an Item by Key

An element can be removed from a dictionary using the pop() method if the key of the element is known. It removes the key and returns its value.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

removed = students.pop(1)

print(students) # {'name': 'Alice', 'age': '22', 'gender': 'Female'}
print(removed) # {'name': 'Tom', 'age': '23', 'gender': 'Male'}

Otherwise, if you don’t need the removed value, you can use the del statement.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

del students[1]

print(students) # {'name': 'Alice', 'age': '22', 'gender': 'Female'}

Remove Last Inserted Item

The popitem() method removes and returns the last inserted item as a tuple.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'}}

removed = students.popitem()

print(students) # {'name': 'Alice', 'age': '22', 'gender': 'Female'}
print(removed) # ('1', {'name': 'Tom', 'age': '23', 'gender': 'Male'})
note

In Python versions before 3.7, popitem() would remove a random item.

Iterate Through a Nested Dictionary

You can iterate over all the values in a nested dictionary using a nested for loop.

students = {1: {'name': 'Tom', 'age': '23', 'gender': 'Male'},
2: {'name': 'Alice', 'age': '22', 'gender': 'Female'},
3: {'name': 'Ryan', 'age': '27', 'gender': 'Male'}}

for id, info in students.items():
print("\nStudent Id:", id)
for key in info:
print(key + ':', info[key])

Output

Student Id: 1
name: Tom
age: 23
gender: Male

Student Id: 2
name: Alice
age: 22
gender: Female

Student Id:3
name: Ryan
age: 27
gender: Male