Nested dictionary – Python

Python Dictionary stores elements in key-value pairs. There are various properties of dictionaries, that we learned in article – create dictionary in Python.

In previous articles, we learned about different ways to add elements in dictionary and remove elements from dictionary. In this article, we will learn about nested dictionary and to various ways to copy dictionary into another dictionary.

Nested Dictionary

Dictionary can store any collection datatype (including dictionary) as a value of the key. Using this we can store another dictionary as a value and can create nested dictionaries.

General example of nested dictionary:

# Example of a Python dictionary
employee = {
    "employee_id": 1001,
    "name": "Allen Smith",
    "department": "Engineering",
    "position": "Software Engineer",
    "salary": 65000,
    "skills": ["Python", "JavaScript", "SQL", "Machine Learning"],
    "manager": {                    # nested dictionary
        "name": "Bob Park",
        "department": "Engineering"
    },
    "full_time": True
}

In this example, we have defined a dictionary employee. Dictionary employee has many key-value elements in it. One element key manager, it has value as another dictionary. Being a value of a key as another dictionary makes it a nested dictionary.

Create Nested Dictionary

Nested dictionary can be created in similar ways other dictionary was created. Nested dictionary can be declared and initialized using either curly braces {} or the dict() constructor.

# create nested dictionary
print("create nested dictionary")
course1_dict = {"name": "Python", "duration": 50}
course2_dict = {"name": "AWS", "duration": 52}
course3_dict = {"name": "Azure", "duration": 50}
courses_dict = {"c1": course1_dict, "c2": course2_dict, "c3": course3_dict}
print(courses_dict)

# dictionary of dictionaries
print("dictionary of dictionaries")
nested_dict = dict({"courses": {"c1": "Python", "c2": "AWS"}})
print(nested_dict)
print(type(nested_dict))

We have covered two scenarios in this program. One to create nested dictionary with curly braces {} and another to create nested dictionary using dict() constructor

  1. Using curly braces {} – In this scenario, we have created three basic dictionaries course1_dict, course2_dict and course3_dict. We are using these dictionaries as a key value to another dictionary courses_dict. Dictionary courses_dict is a nested dictionary, where its each key value is also a dictionary.
  2. Using dict() constructor – In this scenario, we are creating a dictionary nested_dict using dict() constructor. nested_dict dictionary key value is also a dictionary.

Program Output

create nested dictionary
{'c1': {'name': 'Python', 'duration': 50}, 'c2': {'name': 'AWS', 'duration': 52}, 'c3': {'name': 'Azure', 'duration': 50}}

dictionary of dictionaries
{'courses': {'c1': 'Python', 'c2': 'AWS'}}
<class 'dict'>

From the program output, we got nested dictionary in both the scenarios. Nested dictionary class type will be <class 'dict'>.

Access elements in nested dictionary

Elements in nested dictionary can be accessed in similar way as we access elements in other dictionaries. We can access 2nd level, 3rd level and others nested elements from a nested dictionary.

# access elements in nested structure
print("access elements in nested structure")

student_dict = {
    'student_1': {
        'name': 'Johnson',
        'course': {'name': 'Data Science','subjects': ['Python', 'Data Structures', 'Machine Learning']}
    },
    'student_2': {
        'name': 'Smith',
        'course': {'name': 'Web Development', 'subjects': ['Java', 'Spring Boot', 'Microservices']}
    }
}

print(student_dict["student_1"]["course"])    # Access 2nd level nested element
print(student_dict["student_2"]["course"]["subjects"])   # Access 3rd level nested element

In this program, using student_dict["student_1"]["course"] we are accessing value of 2nd level key course which is nested in value of key student_1. Similarly, using student_dict["student_2"]["course"]["subjects"] we are going 3 level deep to access the value of key student_2 => course => subjects.

Program Output

access elements in nested structure
{'name': 'Data Science', 'subjects': ['Python', 'Data Structures', 'Machine Learning']}  # value of course
['Java', 'Spring Boot', 'Microservices']  # value of subjects

Dictionary reference to another dictionary

Similar to assignment of reference from one variable to another variable, we can assign dictionary reference as well.

dictionary_2 = dictionary_1

Let say we have a dictionary which is referenced by dictionary_1. Now if we assign this variable reference to another dictionary dictionary_2, then dictionary_2 will also reference to same dictionary elements and their memory locations.

# reference one dictionary with another
print("reference one dictionary with another")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(courses)
subjects = courses     # assign courses dictionary to subjects dictionary
print(subjects)
subjects["c5"] = "ML"
print(courses)

In this program, we have declared and initialized a dictionary which is referenced by courses. We are assigning courses dictionary reference to another variable subjects. Now, subjects and courses will refer same elements. If we will change elements via any variable, the elements referenced by another variable will also change. Using subjects["c5"] = "ML", we are adding new key-value pair using subjects variable. Values printed with courses variable will show new key-value pair added.

Program Output

reference one dictionary with another
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}    # elements using courses variable
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}    # elements using subjects variable
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java', 'c5': 'ML'}   # elements using courses variable, but added via subject

From the output, elements printed using the courses variable has the new element added in it.

Summary

In this article, we learned about nested dictionary in Python. We learned about:

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *