Python Tutoring Online
 Home

Python Nested Dictionaries

A nested dictionary is a dictionary that contains another dictionary as its value. This allows you to represent complex and structured data in Python programs.

Nested dictionaries are commonly used to store hierarchical data such as student records, employee information, configuration files and JSON data.

Syntax

The syntax of a nested dictionary is similar to a normal dictionary, except that one or more values are themselves dictionaries.

Python
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}

print(students)

Output


{'student1': {'name': 'Alice', 'age': 21}, 'student2': {'name': 'Bob', 'age': 22}}

Example 1: Student Database Using Nested Dictionary

Python
students = {
"student1": {"name": "Alice", "age": 21, "course": "Python"},
"student2": {"name": "Bob", "age": 22, "course": "Data Science"},
"student3": {"name": "Charlie", "age": 23, "course": "Machine Learning"}
}

print(students)

Accessing Values in a Nested Dictionary

To access elements inside a nested dictionary, you must use multiple keys.

Python
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}

print(students["student1"]["name"])

Output


Alice

Example 2: Access Multiple Nested Values

Python
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}

print(students["student2"]["age"])

Adding Elements to Nested Dictionaries

You can add new key-value pairs inside a nested dictionary.

Python
students = {
"student1": {"name": "Alice", "age": 21}
}

students["student1"]["course"] = "Python"

print(students)

Adding a New Nested Dictionary

Python
students = {
"student1": {"name": "Alice", "age": 21}
}

students["student2"] = {"name": "Bob", "age": 22}

print(students)

Modifying Values in Nested Dictionaries

Python
students = {
"student1": {"name": "Alice", "age": 21}
}

students["student1"]["age"] = 22

print(students)

Looping Through Nested Dictionaries

You can use loops to iterate through nested dictionaries.

Python
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 22}
}

for student, info in students.items():
    print(student)
    for key, value in info.items():
        print(key, ":", value)

Real World Example: Product Inventory

Python
products = {
"p1": {"name": "Laptop", "price": 1200, "stock": 10},
"p2": {"name": "Phone", "price": 800, "stock": 20}
}

print(products["p1"]["price"])

Summary

Common Beginner Mistakes

Related Python Dictionary Tutorials




Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net