Welcome to The Coding College, your trusted resource for mastering programming concepts! In this tutorial, we’ll explore nested dictionaries in Python. These powerful data structures allow you to store and manage complex, hierarchical data with ease.
What is a Nested Dictionary?
A nested dictionary is a dictionary that contains one or more dictionaries as values. This structure is ideal for representing hierarchical data, such as a collection of records or settings with multiple levels of detail.
Example:
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
In this example, each key ("person1"
, "person2"
) maps to another dictionary containing details like name
and age
.
Creating Nested Dictionaries
You can create a nested dictionary in multiple ways:
Direct Assignment
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
Using the dict()
Constructor
nested_dict = dict(
person1=dict(name="Alice", age=25),
person2=dict(name="Bob", age=30)
)
Accessing Items in Nested Dictionaries
To access values in a nested dictionary, use the key for each level.
Example:
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
# Access a specific value
print(nested_dict["person1"]["name"]) # Output: Alice
Adding or Updating Nested Dictionary Items
Adding a New Entry
nested_dict["person3"] = {"name": "Charlie", "age": 35}
print(nested_dict)
Updating an Existing Entry
nested_dict["person1"]["age"] = 26
print(nested_dict["person1"]) # Output: {'name': 'Alice', 'age': 26}
Looping Through Nested Dictionaries
Use nested loops to iterate through all levels of a nested dictionary.
Example:
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
# Loop through outer dictionary
for person, details in nested_dict.items():
print(f"{person}:")
# Loop through inner dictionary
for key, value in details.items():
print(f" {key}: {value}")
Output:
person1:
name: Alice
age: 25
person2:
name: Bob
age: 30
Removing Items from Nested Dictionaries
To remove items, use the del
keyword with the appropriate keys.
Example:
del nested_dict["person1"]["age"]
print(nested_dict["person1"]) # Output: {'name': 'Alice'}
To remove an entire nested dictionary:
del nested_dict["person2"]
print(nested_dict) # Output: {'person1': {'name': 'Alice'}}
Practical Applications of Nested Dictionaries
- Database Representation: Use nested dictionaries to simulate records in a database.
- Configuration Settings: Store multi-level application settings.
- Data Transformation: Organize data hierarchically for easier processing.
Example: Representing a Database of Students
students = {
"student1": {"name": "Alice", "grades": {"math": 90, "science": 85}},
"student2": {"name": "Bob", "grades": {"math": 80, "science": 88}}
}
# Access Bob's science grade
print(students["student2"]["grades"]["science"]) # Output: 88
Practice Exercises
Exercise 1: Create a Nested Dictionary
Create a nested dictionary representing employees with name
, department
, and salary
.
Exercise 2: Update Nested Dictionary
Given the following dictionary:
products = {
"item1": {"name": "Laptop", "price": 1000},
"item2": {"name": "Phone", "price": 800}
}
- Update the price of
"Phone"
to750
.
Exercise 3: Loop Through Nested Dictionaries
Using the students
example above, write a loop to print each student’s name and their grades.
Why Learn with The Coding College?
At The Coding College, we believe in making coding concepts accessible and practical. Mastering nested dictionaries equips you to manage complex data structures effectively in real-world applications.
Conclusion
Nested dictionaries are an essential tool for working with hierarchical data in Python. By learning to create, access, modify, and loop through them, you can tackle advanced programming tasks with ease.