PYTHON
Accessing and Updating Nested Dictionaries
Master how to efficiently navigate, access, and modify data within complex, nested dictionary structures in Python, simulating common JSON interactions.
api_response = {
"status": "success",
"data": {
"user": {
"id": 123,
"name": "Alice",
"contact": {
"email": "[email protected]",
"phone": "555-1234"
},
"preferences": {
"notifications": True,
"theme": "dark"
}
},
"products": [
{"item_id": "P001", "name": "Tablet", "price": 499},
{"item_id": "P002", "name": "Headphones", "price": 99}
]
}
}
# Accessing nested data
user_name = api_response['data']['user']['name']
user_email = api_response['data']['user']['contact']['email']
first_product_name = api_response['data']['products'][0]['name']
print(f"User Name: {user_name}")
print(f"User Email: {user_email}")
print(f"First Product: {first_product_name}")
# Modifying nested data
api_response['data']['user']['contact']['phone'] = '555-9876'
api_response['data']['user']['preferences']['theme'] = 'light'
api_response['data']['products'][1]['price'] = 109
print(f"Updated Phone: {api_response['data']['user']['contact']['phone']}")
print(f"Updated Theme: {api_response['data']['user']['preferences']['theme']}")
print(f"Updated Product 2 Price: {api_response['data']['products'][1]['price']}")
# Adding new nested data
api_response['data']['user']['address'] = {
'street': '123 Main St',
'city': 'Anytown'
}
print(f"User Address: {api_response['data']['user']['address']}")
How it works: Web applications frequently handle data structured as nested dictionaries (often parsed from JSON). This snippet demonstrates how to access specific values using chained key lookups, modify existing values, and add new keys and nested structures. Understanding this is crucial for effectively working with APIs, processing configuration data, and manipulating complex data payloads.