Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Nested Dictionaries (Complete Guide for Beginners)

 A nested dictionary in Python is a dictionary inside another dictionary. It allows you to store complex data structures in a structured and organized way.

Nested dictionaries are commonly used in real-world applications like:

  • User management systems
  • Student records
  • Product inventories
  • JSON data handling

In this tutorial, you will learn how nested dictionaries work with clear examples.


What is a Nested Dictionary?

A nested dictionary is a dictionary that contains one or more dictionaries as values.

Example

students = {
    "student1": {"name": "John", "age": 20},
    "student2": {"name": "Alice", "age": 22}
}

Accessing Nested Dictionary Items

You can access nested values using multiple keys.

Example

students = {
    "student1": {"name": "John", "age": 20},
    "student2": {"name": "Alice", "age": 22}
}

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

Output

John

Explanation

  • First key selects the main dictionary
  • Second key selects the nested dictionary value

Accessing Deeper Nested Values

Example

data = {
    "user1": {
        "profile": {
            "name": "David",
            "city": "London"
        }
    }
}

print(data["user1"]["profile"]["city"])

Output

London

Modifying Nested Dictionary Values

You can update values inside nested dictionaries.

Example

students = {
    "student1": {"name": "John", "age": 20}
}

students["student1"]["age"] = 21

print(students)

Output

{'student1': {'name': 'John', 'age': 21}}

Adding Items to Nested Dictionary

Example

students = {
    "student1": {"name": "John", "age": 20}
}

students["student1"]["grade"] = "A"

print(students)

Output

{'student1': {'name': 'John', 'age': 20, 'grade': 'A'}}

Adding New Nested Dictionary

Example

students = {}

students["student1"] = {
    "name": "John",
    "age": 20
}

students["student2"] = {
    "name": "Alice",
    "age": 22
}

print(students)

Loop Through Nested Dictionary

Example

students = {
    "student1": {"name": "John", "age": 20},
    "student2": {"name": "Alice", "age": 22}
}

for student_id, info in students.items():
    print(student_id)
    for key, value in info.items():
        print(" ", key, ":", value)

Output

student1
  name : John
  age : 20
student2
  name : Alice
  age : 22

Delete Items in Nested Dictionary

Example

students = {
    "student1": {"name": "John", "age": 20, "grade": "A"}
}

del students["student1"]["grade"]

print(students)

Output

{'student1': {'name': 'John', 'age': 20}}

Real-World Example: Student Database

school = {
    "student1": {
        "name": "John",
        "age": 20,
        "marks": {
            "math": 85,
            "science": 90
        }
    },
    "student2": {
        "name": "Alice",
        "age": 22,
        "marks": {
            "math": 88,
            "science": 92
        }
    }
}

print(school["student1"]["marks"]["science"])

Output

90

Real-World Example: Product Catalog

products = {
    "laptop": {
        "brand": "Dell",
        "specs": {
            "ram": "16GB",
            "storage": "512GB SSD"
        }
    },
    "phone": {
        "brand": "Samsung",
        "specs": {
            "ram": "8GB",
            "storage": "128GB"
        }
    }
}

print(products["laptop"]["specs"]["ram"])

Advantages of Nested Dictionaries

  • Organize complex data easily
  • Store structured information
  • Work like JSON data
  • Useful in APIs and databases
  • Easy data grouping

Common Mistakes

Mistake 1: Key Error in Nested Access

❌ Wrong

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

If key does not exist, Python raises an error.


Mistake 2: Forgetting Intermediate Keys

❌ Wrong

print(students["name"])

✔ Correct way:

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

Nested Dictionary Methods Summary

OperationExample
Access valuedict[key1][key2]
Add itemdict[key][new_key] = value
Update valuedict[key][key] = value
Delete itemdel dict[key][key]
LoopNested for loops

Practice Exercise 1

Print Alice's age.

students = {
    "student1": {"name": "John", "age": 20},
    "student2": {"name": "Alice", "age": 22}
}

Practice Exercise 2

Add a new subject score inside marks.

student = {
    "name": "Tom",
    "marks": {"math": 80}
}

Conclusion

Nested dictionaries are powerful tools in Python for handling complex and structured data.

You learned:

  • How to create nested dictionaries
  • How to access and modify data
  • How to loop through nested structures
  • Real-world use cases like students and products

Mastering nested dictionaries is essential for working with APIs, JSON, databases, and real-world applications.




Post a Comment

0 Comments