Nested Dictionary in Python

In this tutorial, We are going to learn about Nested dictionary in Python. First of all, let us know about dictionaries in Python. So it’ll be easy to implement nested dictionaries. After this tutorial, you will be able to create dictionaries and be able to modify them.

Dictionary is an unordered collection of data that contains keys and values, which are changeable and indexable. It holds the key: value pair. Dictionaries are declared by enclosing elements within curly braces {}. Dictionary support values of any datatype and similarly, duplication is also possible. But the keys should be immutable. Keys are case sensitive.

Example:-

a = {'Name':'Tony','age':21,'Height':5.10}
print(a)

Output:-

{'Name': 'Tony', 'age': 21, 'Height': 5.1}

Nested Dictionaries in Python

Nested dictionary means a dictionary inside a dictionary. Therefore, it is a collection of all dictionaries into one dictionary. For example, we are going to create a dictionary of marks of students.

marks = {'John':{'Math':90,'Physics':80,'Chemistry':75.5},
'Susan':{'Math':80,'Physics':95,'Chemistry':60}}
print(marks)

Output:-

{'John': {'Math': 90, 'Physics': 80, 'Chemistry': 75.5}, 'Susan': {'Math': 80, 'Physics': 95, 'Chemistry': 60}}

In the above example, the marks dictionary consists of marks of two students in the dictionary format. Therefore marks is a nested dictionary. Because we have placed two similar dictionaries of marks inside it.

Deleting variables from a nested dictionary in Python

A variable is deleted using the del keyword.

marks = {'John':{'Math':90,'Physics':80,'Chemistry':75.5},
'Susan':{'Math':80,'Physics':95,'Chemistry':60}}
del(marks['John'])
print(marks)

Output:-

{'Susan': {'Math': 80, 'Physics': 95, 'Chemistry': 60}}

In the above example, we are deleting the dictionary of John with del keyword. So as a result, the output only contains Susan’s details.

Accessing variables from a nested dictionary in Python

Accessing a variable from a nested dictionary is similar to accessing it from lists and dictionaries. In other words, it is similar to indexing.
Example:-

marks = {'John':{'Math':90,'Physics':80,'Chemistry':75.5},
'Susan':{'Math':80,'Physics':95,'Chemistry':60}}
print(marks['John']['Math'])

Output:-

90

Adding elements to a nested dictionary:

Lastly, we are going to learn to add elements in a dictionary. Here we are going to add marks of another student which is similar to John and Susan.

marks = {'John':{'Math':90,'Physics':80,'Chemistry':75.5},
'Susan':{'Math':80,'Physics':95,'Chemistry':60}}
a['Aaron'] = {}
a['Aaron']['Math'] = 70
print(marks)

Output:-

{'John': {'Math': 90, 'Physics': 80, 'Chemistry': 75.5}, 'Susan': {'Math': 80, 'Physics': 95, 'Chemistry': 60}, 'Aaron': {'Math': 70}}

Also, read:- Converting a List into a Dictionary in Python

Leave a Reply