7.1 Creating Nested Dictionaries
Nested dictionaries are a super handy way to describe complex data structures, and you are going to encounter them quite often. Let's get some practice on creating them.
Creating Nested Dictionaries
Here's an example of creating a nested dictionary:
person = {
"name": "Alice",
"details": {
"age": 25,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"mother": "Jane Smith"
},
"gender": "female"
}
print(person) # Output: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}, 'mother': 'Jane Smith'}, 'gender': 'female'}
In this case, person
is a dictionary containing a nested dictionary details
, which in turn contains another nested dictionary address
.
You can also create a nested dictionary from pieces:
address = {
"street": "123 Main St",
"zip": "10001"
}
details = {
"age": 25,
"city": "New York",
"address": address
}
person = {
"name": "Alice",
"details": details,
"gender": "female"
}
print(person) # Output: {'name': 'Alice', 'details': {'age': 25, 'city': 'New York', 'address': {'street': '123 Main St', 'zip': '10001'}}, 'gender': 'female'}
7.2 Accessing Elements of Nested Dictionaries
Accessing elements within nested dictionaries is simple and straightforward. Here's how you do it:
Accessing Top-Level Elements
name = person["name"]
print(name) # Output: Alice
Accessing Elements of a Nested Dictionary
age = person["details"]["age"]
city = person["details"]["city"]
print(age) # Output: 25
print(city) # Output: New York
Accessing Deeper Levels of Nested Elements
street = person["details"]["address"]["street"]
zip_code = person["details"]["address"]["zip"]
print(street) # Output: 123 Main St
print(zip_code) # Output: 10001
7.3 Modifying Elements of Nested Dictionaries
If you’ve figured out how to access elements at any depth, modifying them will be even easier:
Changing Top-Level Values
person["name"] = "Bob"
print(person["name"]) # Output: Bob
Changing Values in a Nested Dictionary
person["details"]["age"] = 26
print(person["details"]["age"]) # Output: 26
Changing Values at a Deeper Level of Nesting
person["details"]["address"]["city"] = "Los Angeles"
print(person["details"]["address"]["city"]) # Output: Los Angeles
Adding New Elements to a Nested Dictionary
person["details"]["phone"] = "123-456-7890"
print(person["details"]["phone"]) # Output: 123-456-7890
Removing Top-Level Elements
# Removing 'country' element from 'person' dictionary
del person["country"]
print(person) # 'country' element will be removed from dictionary
Removing Elements from a Nested Dictionary
# Removing 'phone' element from 'details' dictionary
del person["details"]["phone"]
print(person["details"]) # 'phone' element will be removed from 'details' dictionary
7.4 Iterating Over Nested Dictionaries
There are a few ways to iterate through all elements in a dictionary. Loops are the simplest:
Iterating Through Elements of a Nested Dictionary
for key, value in person.items(): # Iterating parent dictionary
if isinstance(value, dict): # If the value is a dictionary
for key2, value2 in value.items(): # Iterate child dictionary elements
print(f"{key} --> {key2}: {value2}")
Recursive Iteration Through All Levels of Nesting
def print_dict(d, indent=0):
for key, value in d.items():
print(" " * indent + str(key) + ": ", end="")
if isinstance(value, dict):
print()
print_dict(value, indent + 1)
else:
print(value)
print_dict(person)
You'll learn more about recursion in the "Algorithms and Data Structures" section.
By the way, recursion is pretty handy for finding a value deep inside nested dictionaries. Here's an example:
def find_key(d, key):
if key in d:
return d[key]
for k, v in d.items():
if isinstance(v, dict):
result = find_key(v, key)
if result:
return result
return None
phone = find_key(person, "phone")
print(phone) # Output: None (since 'phone' element was removed)
GO TO FULL VERSION