← Back to Chapters

Python Nested Dictionaries

? Python Nested Dictionaries

⚡ Quick Overview

A nested dictionary is a dictionary that contains one or more dictionaries as values. It is useful for storing structured or hierarchical data such as students, products, configuration settings, or JSON-like data.

? Key Concepts

  • A nested dictionary is simply “a dictionary inside a dictionary”.
  • The outer dictionary keys usually represent unique IDs like "student1", "student2".
  • The inner dictionary stores the details of that ID, such as name, age, city, etc.
  • You access values by chaining keys, for example: students["student1"]["name"].
  • You can add, modify, or delete inner keys just like in a normal dictionary.

? Syntax and Structure

A typical nested dictionary structure looks like this:

? Nested Dictionary Structure
# Outer dictionary with inner dictionaries as values
outer_dict = {
    "key1": {"inner_key1": "value1", "inner_key2": "value2"},
    "key2": {"inner_key1": "value3", "inner_key2": "value4"}
}

In our student example, each key like "student1" maps to another dictionary containing that student's details.

? Use Cases

  • Maintaining records of multiple users, students, or employees with several attributes.
  • Working with JSON data from web APIs (which maps naturally to nested dictionaries).
  • Grouping related configuration options by sections or categories.

? Code Examples

? Creating a Nested Dictionary

Here is a nested dictionary that stores information about two students:

# Create a nested dictionary for two students
students = {
    "student1": {"name": "Alice", "age": 25},
    "student2": {"name": "Bob", "age": 24}
}
# Print the entire nested dictionary
print(students)
? Accessing Values in a Nested Dictionary

Access nested values by using the outer key first, then the inner key:

print(students["student1"]["name"])  # Alice
print(students["student2"]["age"])   # 24
✏️ Modifying Values in Nested Dictionaries

Modify inner values just like updating a normal dictionary:

# Update the age of student1
students["student1"]["age"] = 26
print(students["student1"]["age"])  # 26
➕ Adding New Items to Nested Dictionaries

You can add a new student or new fields to an existing student:

# Add a new student entry
students["student3"] = {"name": "Charlie", "age": 23}
# Add a new field to an existing student
students["student1"]["city"] = "New York"
# Print the updated nested dictionary
print(students)
? Looping Through a Nested Dictionary

Use nested loops to go through each student and their details:

# Loop through each student and their details
for student_id, details in students.items():
    print("ID:", student_id)
    # Inner loop over each field in the student's info
    for key, value in details.items():
        print(" ", key + ":", value)

? Live Output and Explanation

This example creates the dictionary, updates it, and then prints each student's details:

▶️ Full Example with Output
# Create the initial nested dictionary of students
students = {
    "student1": {"name": "Alice", "age": 25},
    "student2": {"name": "Bob", "age": 24}
}

# Add a city for student1 and a new student3
students["student1"]["city"] = "New York"
students["student3"] = {"name": "Charlie", "age": 23}

# Loop through the dictionary and print each student's details
for sid, info in students.items():
    print("ID:", sid)
    print(" Name:", info["name"])
    print(" Age:", info["age"])
    if "city" in info:
        # Only print city if the key exists
        print(" City:", info["city"])
    print()

?️ Sample Output

The output in the terminal will look like:

ID: student1
 Name: Alice
 Age: 25
 City: New York

ID: student2
 Name: Bob
 Age: 24

ID: student3
 Name: Charlie
 Age: 23

The condition if "city" in info ensures we only print the city when that key exists, preventing a KeyError.

? Tips & Best Practices

  • Nested dictionaries are excellent for representing JSON-like structured data.
  • Use in or dict.get() to safely check keys before accessing nested values.
  • Use nested for loops to iterate over outer and inner dictionaries.
  • Be careful with copying: a shallow copy shares inner dictionaries. Use copy.deepcopy() for fully independent copies.
  • Keep your key naming consistent across all inner dictionaries (for example, always use "name", not a mix of "name" and "full_name").

? Try It Yourself

  • Create a nested dictionary for 3 students with keys like name and age.
  • Access and print the name of student2 using chained keys.
  • Add a city key to student1 and assign a value.
  • Loop through all students and print their details in a clean, formatted way.
  • Add another field, such as "marks" or "course", and display it in your loop.