π§© Python Nested Dictionaries β Storing Complex Data Made Easy | TechTown.in
Need to store detailed, structured data in Python? Thatβs where nested dictionaries come in!
A nested dictionary is simply a dictionary inside another dictionary. It allows you to organize complex datasets in a clean and readable format β making it perfect for representing users, products, students, or API responses.
In this article, you’ll learn how to create, access, update, and manage nested dictionaries with real-world examples.
π What is a Nested Dictionary?
A nested dictionary means that the value of a key is another dictionary.
students = {
"student1": {"name": "Tanmay", "age": 22},
"student2": {"name": "Aditi", "age": 21}
}
Each key (student1, student2) maps to another dictionary containing personal info.
π¦ Creating Nested Dictionaries
You can define them all at once:
users = {
"user1": {"username": "techtown", "role": "admin"},
"user2": {"username": "guest", "role": "viewer"}
}
Or build them step-by-step:
users = {}
users["user1"] = {"username": "techtown", "role": "admin"}
π Accessing Items in Nested Dictionaries
Use double keys to drill down:
print(users["user1"]["username"]) # Output: techtown
You can also loop through it:
for user_id, user_info in users.items():
print(user_id, "β", user_info["username"], "| Role:", user_info["role"])
βοΈ Updating Nested Values
users["user2"]["role"] = "editor"
β Updates the value inside the inner dictionary.
β Adding New Sub-Dictionaries
users["user3"] = {"username": "newuser", "role": "guest"}
β Great for dynamic data, like adding new records from a form or API.
β Deleting Nested Data
del users["user1"]["role"] # Removes 'role' from user1
del users["user3"] # Deletes entire user3 entry
π§ Real-World Use Cases for Nested Dictionaries
- Student Records: ID β details (name, age, subjects)
- Inventory Systems: Product ID β specs (brand, price, stock)
- User Management: User ID β profile info (email, role, login status)
- API Responses: JSON data parsed as nested dictionaries
π Summary β Nested Dictionary Basics
| Operation | Example |
|---|---|
| Access inner value | dict["key1"]["key2"] |
| Update inner value | dict["key1"]["key2"] = new_value |
| Add inner dictionary | dict["newkey"] = {"a": 1, "b": 2} |
| Loop through nested | for key, subdict in dict.items(): |
| Delete inner value | del dict["key1"]["key2"] |
π Final Thoughts
Nested dictionaries are perfect for organizing hierarchical or grouped data in Python. They’re widely used in data science, APIs, web apps, and real-world systems where structured information is key.
Once you’re comfortable with regular dictionaries, nested ones unlock an entirely new level of power and flexibility!
π Learn more about Python data structures at TechTown.in