Python Nested Dictionaries

What is a Nested Dictionary?

A nested dictionary means having a dictionary inside another dictionary. It allows you to store hierarchical, grouped, or structured data.

Example 1: Creating a Nested Dictionary

students = {
 "student1": {
   "name": "Alice",
   "age": 20
 },
 "student2": {
   "name": "Bob",
   "age": 22
 }
}
print(students)

Output:

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

Explanation: students is a dictionary where each key holds another dictionary as its value.

Example 2: Access Nested Dictionary Items

students = {
 "student1": {
   "name": "Alice",
   "age": 20
 },
 "student2": {
   "name": "Bob",
   "age": 22
 }
}
print(students["student1"]["name"])

Output:

Alice

Explanation: First, access "student1" dictionary, then "name" inside it.

Example 3: Modify Nested Dictionary Item

students = {
 "student1": {
   "name": "Alice",
   "age": 20
 },
 "student2": {
   "name": "Bob",
   "age": 22
 }
}
students["student2"]["age"] = 23
print(students["student2"])

Output:

{'name': 'Bob', 'age': 23}

Explanation: The age of student2 is updated using standard key access.

Example 4: Add a New Dictionary Inside

students = {
 "student1": {
   "name": "Alice",
   "age": 20
 },
 "student2": {
   "name": "Bob",
   "age": 22
 }
}
students["student3"] = {
 "name": "Charlie",
 "age": 21
}
print(students["student3"])

Output:

{'name': 'Charlie', 'age': 21}

Explanation: We added a new nested dictionary under the key "student3".

Example 5: Loop Through Nested Dictionary

students = {
 "student1": {
   "name": "Alice",
   "age": 20
 },
 "student2": {
   "name": "Bob",
   "age": 22
 }
  "student3": {
   "name": "Charlie",
   "age": 21
 }
}
for key, value in students.items():
   print(key)
   for sub_key, sub_value in value.items():
       print(f"  {sub_key}: {sub_value}")

Output:

student1
 name: Alice
 age: 20
student2
 name: Bob
 age: 23
student3
 name: Charlie
 age: 21

Explanation: Outer loop goes through each student, inner loop goes through their details.

Example 6: Using dict() to Build Nested Dictionary Dynamically

student1 = dict(name="Eve", age=19)
student2 = dict(name="Frank", age=24)
students = {
 "student1": student1,
 "student2": student2
}
print(students)

Output:

{'student1': {'name': 'Eve', 'age': 19}, 'student2': {'name': 'Frank', 'age': 24}}

Explanation: You can build inner dictionaries separately and then combine them.

Conclusion

Nested dictionaries help manage structured data, such as records or categories. Access them using multiple keys, and loop through them using nested for loops.