Nested Dictionaries
4 min read ·
A nested dictionary is a dictionary that contains another dictionary as its value.
Nested dictionaries are used to represent complex, structured, real-world data such as users, students, employees, products, configurations, and JSON-like data.
In Python, nested dictionaries are very common in:
- APIs
- Databases
- Configuration files
- Data processing
- Backend systems
What Is a Nested Dictionary
A dictionary inside another dictionary.
Text concept:
Dictionary
└── Key
└── Value (another dictionary)
Basic Example of Nested Dictionary
Here:
- Outer dictionary →
students - Inner dictionaries → student details
Access Nested Dictionary Items
Access Inner Dictionary
Access Specific Value
Safe Access Using get()
This avoids errors if keys are missing.
Loop Through Nested Dictionaries
Loop Through Outer Dictionary
Loop Through Inner Dictionaries
Add New Item to Nested Dictionary
Add New Key Inside Inner Dictionary
Add New Nested Dictionary
Update Nested Dictionary Values
Update Multiple Values
Remove Items from Nested Dictionary
Remove Inner Key
Remove Entire Nested Dictionary
Check Key Existence in Nested Dictionary
Nested Dictionary with Lists
Very common real-world structure.
Access list inside dictionary:
Loop Through Nested Dictionary with Lists
Nested Dictionary Using Dictionary Comprehension
Create Nested Dictionary Dynamically
Using setdefault() for Nested Dictionaries
This prevents
KeyError while adding nested data.Copying Nested Dictionaries (Important)
Shallow Copy Problem
Both change due to shared reference.
Deep Copy Solution
Nested Dictionary from List of Tuples
JSON-Like Nested Dictionaries
APIs usually return data like this.
Access deep values:
Common Mistakes
Assuming All Keys Exist
Modifying While Looping
Real-World Use Cases
Nested dictionaries are used for:
- User profiles
- Student records
- API responses
- Configuration files
- Database-like structures
- Machine learning datasets
Advanced Concept: Flatten Nested Dictionary
This technique is widely used in data processing and analytics.
Important Insight (New Concept to End Topic)
Most real-world Python data is not flat.
Learning nested dictionaries prepares you to work confidently with:
- APIs
- JSON
- Databases
- Backend systems
- Data engineering pipelines
Mastering nested dictionaries means you are ready to handle production-level Python data structures, not just beginner examples.