Nested Dictionary in Python: Storing Data Made Easy

Whenever we talk about storing data in the form of key-value pair in python, the data structure that comes first into mind is a python dictionary. If you come from a JAVA background, you must be familiar with hash maps and hash tables. If we want to store information in a structured way, creating a nested dictionary in python can be one of the better options.
Nested Dictionary is nothing but a dictionary inside the Dictionary. In nested dictionaries, some keys have another dictionary as its values. Let us look at an example to understand it better.
{“Sameer”:{“English”:91},”Tarun”:{“English”:76},”Archit”:{“English”:92}}
We can see that by using a nested dictionary, we can store information for different students and their marks. And the best thing it is so easy to retrieve. It wouldn’t have been possible with lists or any other data type.

How to Create Nested Lists in Python

Creating a nested dictionary in python is not rocket science. For starters, let us first learn how to create a standard dictionary.

Standard Dictionary

# To create a normal dictionary we can use dict().
dict1=dict()
# key='a', value=20
dict1['a']=20
# key='b', value=21
dict1['b']=21
print("dict1:",dict1)
# Using {}
dict2={}
dict2['c']=50
dict2['d']=51
print("dict2:",dict2)
Output-

dict1: {'a': 20, 'b': 21}
dict2: {'c': 50, 'd': 51}

Nested Dictionary

Method-1

# making an empty dictionary
student_info={}
# Adding value to key='ashwini' as another dictonary
student_info['ashwini'] ={'maths':92,'english':90,'science':80}
student_info['archit'] ={'maths':93,'english':80,'science':90}
student_info['tarun'] ={'maths':82,'english':86,'science':95}
print(student_info)
Output-
{'ashwini': {'maths': 92, 'english': 90, 'science': 80}, 'archit': {'maths': 93, 'english': 80, 'science': 90}, 'tarun': {'maths': 82, 'english': 86, 'science': 95}}

Method 2 Using zip()

# Storing the id's into a list
Employee_id=[1,2,3]
# Storing the info in another dictionary
Employee_info = [ { 'Name': 'Ashish' , 'Age' : 33 , "Designation" : "Web Developer"} , { 'Name' : 'Shubham' , 'Age' : 23 , "Designation" : "IOS APP Developer" } , { 'Name' : 'Vandana' , 'Age' : 25, "Designation" : "Data Scientist" }]
# Mapping the id's with employee information
Employee=dict(zip(Employee_id,Employee_info))
print('Employee Information',Employee)
Output-

Employee Information {1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}}

Adding New Elements in a Nested Dictionary in Python

Suppose we want to add new elements to the pre-created dictionary. Let’s see how we do this.

Method-1

Employee_id=[1,2,3,4,5]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
#Here we are adding new info of Employee with 'id':4
Employee[4]={'Name':'Ashutosh','Age':40,"Designation":"Cyber Security Expert"}
print(Employee[4])
Output-
{'Name': 'Ashutosh', 'Age': 40, 'Designation': 'Cyber Security Expert'}


Method-2

Employee_id=[1,2,3]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
# Create a new dictionary for Employee with id-4
Employee[4]={}
# Adding NAME of Employee
Employee[4]['Name']='Manya'
# Adding AGE of Employee
Employee[4]['Age']=29
# Adding DESIGNATION of Employee
Employee[4]['Designation']='HR'
print(Employee)

Output-

{1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}, 4: {'Name': 'Manya', 'Age': 29, 'Designation': 'HR'}}


You can observe that the new entries have been added at the end successfully.

Method 3-

Suppose if we want to add multiple entries to a dictionary. We can use For loop for that.

Employee_id=[1,2,3]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
# Checking the length of the dictionary before addition
total_employees=len(Employee)
ids=int(input("How many Entries you want to add:"))
# Adding new Employees 
for i in range(total_employees+1,total_employees+ids+1):
    Employee[i]={}
    # Adding NAME of Employee
    Employee[i]['Name']=input("Enter the name of new Employee:")
    # Adding AGE of Employee
    Employee[i]['Age']=int(input("Enter the age of new Employee:"))
    # Adding DESIGNATION of Employee
    Employee[i]['Designation']=input("Enter the designation of new Employee:")
print(Employee)
nested dictionary python
Output-

How many Entries you want to add:4
Enter the name of new Employee:kunal
Enter the age of new Employee:29
Enter the designation of new Employee:Data Analyst
Enter the name of new Employee:Kushal
Enter the age of new Employee:49
Enter the designation of new Employee:System Architect
Enter the name of new Employee:Preeti
Enter the age of new Employee:36
Enter the designation of new Employee:Researcher
Enter the name of new Employee:Aarti
Enter the age of new Employee:22
Enter the designation of new Employee: Content Writer

{1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}, 4: {'Name': 'kunal', 'Age': 29, 'Designation': 'Data Analyst'}, 5: {'Name': 'Kushal', 'Age': 49, 'Designation': 'System Architect'}, 6: {'Name': 'Preeti', 'Age': 36, 'Designation': 'Researcher'}, 7: {'Name': 'Aarti', 'Age': 22, 'Designation': 'Content Writer'}} 

Changing The Values in Nested Dictionaries in Python

In this section, we will learn how to update values in a nested dictionary.
For example, suppose if, in a company, an employee named Ashish, who was working as a web developer, has been promoted to Senior Web Developer. Let’s see how we can update this value.

Employee_id=[1,2,3,4,5]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
print("Employee information before updation",Employee,"\n")
# Iterating through the values in employee dictionary
for i in Employee.values():
    # Look for an employee with name 'Ashish'
    if i['Name']=='Ashish':
        # Change the designation to 'Sr. Web Developer'
        i['Designation']='Sr. Web Developer'
print("Employee information after updation",Employee)

Output-

Employee information before updation {1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}}

Employee information after updation {1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Sr. Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}}

Deleting an Entry in a Nested Dictionary in Python

Suppose if an employee has left the company. Let us have a look at how we will drop that entry.

Employee_id=[1,2,3,4,5]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
print("Employee before Deletion : ",Employee,"\n")
# Delete the employee record with id=2
Employee.pop(2)
print("Employee after Deletion : ",Employee)

Output-

Employee before Deletion : {1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 2: {'Name': 'Shubham', 'Age': 23, 'Designation': 'IOS APP Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}}

Employee after Deletion: {1: {'Name': 'Ashish', 'Age': 33, 'Designation': 'Web Developer'}, 3: {'Name': 'Vandana', 'Age': 25, 'Designation': 'Data Scientist'}}

Retrieving Values from Nested Dictionaries in Python

Let us iterate through this nested Dictionary using for loop.

Employee_id=[1,2,3]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
# Iterating through employee keys
for i in Employee.keys():
    print("Employee Id:",i)
# Iterating through the values of Employee keys
    for j in Employee[i]:
        print(j,":",Employee[i][j])
    print("\n")

Output-

Employee Id: 1
Name : Ashish
Age : 33
Designation: Web Developer

Employee Id: 2
Name: Shubham
Age: 23
Designation: IOS APP Developer

Employee Id: 3
Name : Vandana
Age : 25
Designation : Data Scientist

Now, if we want to directly access the age of Employee with id=2

Employee_id=[1,2,3]
Employee_info=[{'Name':'Ashish','Age':33,"Designation":"Web Developer"},{'Name':'Shubham','Age':23,"Designation":"IOS APP Developer"},{'Name':'Vandana','Age':25,"Designation":"Data Scientist"}]
Employee=dict(zip(Employee_id,Employee_info))
# Age of employee with id 2
print(Employee[2]['Age'])

Output-

23

Must Read:

Conclusion

Nested dictionaries in python have proved to be very useful when we have to store data in a structured way. We have discussed how to store data in a nested dictionary, how to retrieve the values stored in it, how to delete, and update values from it in many different ways.

Try to run the programs on your side and let us know if you have any queries.

Happy Coding!

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments