Nested Dictionaries
Creating Nested Dictionaries
A nested dictionary is simply a dictionary that contains other dictionaries as values. They are useful for representing structured or hierarchical data, such as records or configurations.
Example
# Creating nested dictionaries
# Method 1: Direct assignment
company = {
"employee1": {"name": "John", "age": 30, "department": "IT"},
"employee2": {"name": "Jane", "age": 25, "department": "HR"}
}
# Method 2: Building incrementally
school = {}
school["student1"] = {"name": "Alice", "grades": {"math": 90, "science": 85}}
school["student2"] = {"name": "Bob", "grades": {"math": 78, "science": 92}}
print("Company:", company)
print("School:", school)
Output
Company: {'employee1': {'name': 'John', 'age': 30, 'department': 'IT'}, 'employee2': {'name': 'Jane', 'age': 25, 'department': 'HR'}} School: {'student1': {'name': 'Alice', 'grades': {'math': 90, 'science': 85}}, 'student2': {'name': 'Bob', 'grades': {'math': 78, 'science': 92}}}
Accessing Nested Data
You can access values in nested dictionaries by chaining key lookups. To prevent errors, use `get()` with default values when the nested key may not exist.
Example
# Accessing nested data
company = {
"employee1": {"name": "John", "age": 30, "department": "IT"},
"employee2": {"name": "Jane", "age": 25, "department": "HR"}
}
# Access nested values
print("Employee1 name:", company["employee1"]["name"])
print("Employee2 department:", company["employee2"]["department"])
# Safe access with get()
age = company.get("employee1", {}).get("age", "Unknown")
print("Employee1 age:", age)
salary = company.get("employee3", {}).get("salary", "Not specified")
print("Employee3 salary:", salary)
Output
Employee1 name: John Employee2 department: HR Employee1 age: 30 Employee3 salary: Not specified
Modifying Nested Dictionaries
You can update values inside nested dictionaries just like regular ones. You can also add new nested dictionaries dynamically.
Example
# Modifying nested dictionaries
company = {
"employee1": {"name": "John", "age": 30, "department": "IT"},
"employee2": {"name": "Jane", "age": 25, "department": "HR"}
}
# Update existing nested values
company["employee1"]["age"] = 31
company["employee2"]["salary"] = 50000
# Add a new nested dictionary
company["employee3"] = {"name": "Bob", "age": 28, "department": "Finance"}
print("Updated company:", company)
Output
Updated company: {'employee1': {'name': 'John', 'age': 31, 'department': 'IT'}, 'employee2': {'name': 'Jane', 'age': 25, 'department': 'HR', 'salary': 50000}, 'employee3': {'name': 'Bob', 'age': 28, 'department': 'Finance'}}
Iterating Through Nested Dictionaries
Nested loops allow you to process keys and values at multiple levels, which is useful for structured data traversal.
Example
# Iterating through nested dictionaries
company = {
"employee1": {"name": "John", "age": 30, "department": "IT"},
"employee2": {"name": "Jane", "age": 25, "department": "HR"}
}
for employee_id, details in company.items():
print(f"\n{employee_id}:")
for key, value in details.items():
print(f" {key}: {value}")
Output
employee1: name: John age: 30 department: IT employee2: name: Jane age: 25 department: HR