🧩 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

OperationExample
Access inner valuedict["key1"]["key2"]
Update inner valuedict["key1"]["key2"] = new_value
Add inner dictionarydict["newkey"] = {"a": 1, "b": 2}
Loop through nestedfor key, subdict in dict.items():
Delete inner valuedel 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