free geoip
14

Python Nested Dictionary Exercises for Beginners

In Python, a nested dictionary is a dictionary inside another dictionary. This powerful data structure allows you to represent complex…

In Python, a nested dictionary is a dictionary inside another dictionary. This powerful data structure allows you to represent complex hierarchical data in a clean and organized way. In this article, you will learn how to create, access, modify, and loop through nested dictionaries in Python with hands-on exercises and detailed explanations. Let’s dive into it!

Python Nested Dictionary Exercises for Beginners

1. What is a Nested Dictionary in Python?

A nested dictionary means a dictionary that contains another dictionary as its value. It’s useful when you need to store structured data, such as student records, product catalogs, or JSON-like data.

# Example of a nested dictionary
students = {
    "John": {"age": 20, "grade": "A"},
    "Alice": {"age": 22, "grade": "B"},
    "Bob": {"age": 19, "grade": "A+"}
}

print(students)

In this example, each student name is a key that holds another dictionary with details like age and grade.

2. Accessing Values in a Nested Dictionary

You can access specific values by chaining the keys.

# Access Alice's grade
print(students["Alice"]["grade"])

# Access Bob's age
print(students["Bob"]["age"])

Output:

B
19

3. Adding and Updating Data

You can add a new entry or update existing data by directly assigning values to keys.

# Add a new student
students["Eve"] = {"age": 21, "grade": "A"}

# Update John's grade
students["John"]["grade"] = "A+"

print(students)

Python makes it simple to modify nested structures dynamically.

4. Looping Through Nested Dictionaries

Iterating through nested dictionaries helps you extract or process data in bulk. Use a for loop to traverse through each key and inner dictionary.

for name, info in students.items():
    print(f"Name: {name}")
    for key, value in info.items():
        print(f"  {key}: {value}")

Output:

Name: John
  age: 20
  grade: A+
Name: Alice
  age: 22
  grade: B
Name: Bob
  age: 19
  grade: A+
Name: Eve
  age: 21
  grade: A

5. Removing Items from a Nested Dictionary

To delete elements, use the del keyword or pop() method.

# Remove Bob from the dictionary
del students["Bob"]

# Remove only a key from John's inner dictionary
students["John"].pop("age")

print(students)

6. Nested Dictionary with Loops and Conditions

You can also use loops and conditional statements together for filtering data. For example, print only students with grade “A” or higher:

for name, details in students.items():
    if details["grade"] in ["A", "A+"]:
        print(f"{name} has a top grade: {details['grade']}")

7. Working with Nested Dictionary Inside a List

Sometimes, you may have a list of nested dictionaries—like a list of products or employees. Here’s an example:

products = [
    {"id": 1, "name": "Laptop", "price": 1200, "specs": {"RAM": "16GB", "SSD": "512GB"}},
    {"id": 2, "name": "Phone", "price": 700, "specs": {"RAM": "8GB", "SSD": "128GB"}},
    {"id": 3, "name": "Tablet", "price": 500, "specs": {"RAM": "6GB", "SSD": "256GB"}}
]

# Access nested values
for product in products:
    print(product["name"], "-", product["specs"]["RAM"])

8. Combining Nested Dictionaries

You can merge two nested dictionaries using the update() method or dictionary comprehension.

dict1 = {"A": {"math": 90}}
dict2 = {"B": {"math": 85}}

dict1.update(dict2)
print(dict1)

9. Practice Exercise

Try solving this short exercise to test your understanding.

# Exercise: Create a dictionary of countries and their cities
world = {
    "USA": {"capital": "Washington, D.C.", "currency": "USD"},
    "Japan": {"capital": "Tokyo", "currency": "Yen"},
    "France": {"capital": "Paris", "currency": "Euro"}
}

# Print the capital of Japan
print(world["Japan"]["capital"])

# Add a new country
world["India"] = {"capital": "New Delhi", "currency": "Rupee"}

# Print all country names and currencies
for country, info in world.items():
    print(f"{country} uses {info['currency']}")

10. Conclusion

Nested dictionaries are one of the most useful Python data structures for representing structured data. They are widely used in JSON manipulation, database results, and data analysis. Understanding how to create, modify, and loop through nested dictionaries is essential for building clean, efficient, and scalable Python programs. Keep practicing these exercises to master the concept.

Recommended Next: Try more Python Dictionary Exercises to improve your data structure skills.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *