Python – Nested Dictionaries

1. What is a Nested Dictionary?

A nested dictionary means a dictionary inside another dictionary.

In simple words:
👉 One dictionary stores another dictionary as its value.

2. Why Use Nested Dictionaries?

We use nested dictionaries when:

  • Data is grouped

  • Data has levels

Examples:

  • Students → details

  • Employees → information

  • Products → price, stock, brand

3. Simple Nested Dictionary Example

Example

students = {
"student1": {
"name": "Amit",
"age": 20
},
"student2": {
"name": "Ravi",
"age": 22
}
}

print(students)

4. Access Nested Dictionary Items

Use two keys to access inner values.

Example

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

Output:

Amit
22

5. Change Value in Nested Dictionary

Example

students["student1"]["age"] = 21
print(students["student1"])

6. Add New Item in Nested Dictionary

Example

students["student1"]["city"] = "Delhi"
print(students["student1"])

7. Add New Dictionary Inside Dictionary

Example

students["student3"] = {
"name": "Sita",
"age": 19
}

print(students)

8. Loop Through Nested Dictionary

Example

for key, value in students.items():
print(key)
for k, v in value.items():
print(" ", k, v)

9. Check Key Exists in Nested Dictionary

Example

if "age" in students["student1"]:
print("Age key exists")

10. Remove Item from Nested Dictionary

Example

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

11. Remove Entire Inner Dictionary

Example

del students["student2"]
print(students)

12. Nested Dictionary with Different Data Types

Example

product = {
"item1": {
"name": "Laptop",
"price": 50000,
"available": True
}
}

print(product)

13. Common Beginner Mistakes

❌ Forgetting Inner Key

print(students["student1"])

👉 This prints the inner dictionary, not the value.

❌ Accessing Missing Key

print(students["student3"]["marks"])

✔ Safe way:

print(students["student3"].get("marks"))

14. Simple Practice Examples

Example 1: Employee Data

employees = {
"emp1": {"name": "Ravi", "salary": 30000},
"emp2": {"name": "Amit", "salary": 40000}
}

print(employees["emp2"]["salary"])

Example 2: Update Salary

employees["emp1"]["salary"] = 35000
print(employees["emp1"])

Example 3: Loop Employees

for emp, info in employees.items():
print(emp, info["name"])

15. Summary (Nested Dictionaries)

✔ Dictionary inside dictionary
✔ Use multiple keys to access
✔ Useful for grouped data
✔ Can loop easily
✔ Very common in real programs

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Dictionary Methods

  • Dictionary Exercises

  • Mini Python Projects

  • JSON vs Dictionary

Just tell me 😊

You may also like...