PYTHON
Merging and Safely Accessing Nested Dictionaries
Learn how to efficiently merge Python dictionaries using `**` and `update()`, and safely access nested values with `get()` to prevent KeyErrors in web data.
# Merging dictionaries
dict1 = {'name': 'Alice', 'age': 30}
dict2 = {'city': 'New York', 'occupation': 'Engineer'}
dict3 = {'age': 31, 'email': '[email protected]'}
# Method 1: Using dict.update() (modifies dict1)
merged_dict_update = dict1.copy() # Make a copy if you don't want to modify dict1
merged_dict_update.update(dict2)
merged_dict_update.update(dict3)
print(f"Merged with update: {merged_dict_update}")
# Method 2: Using the ** operator (Python 3.5+) - creates a new dictionary
merged_dict_unpacking = {**dict1, **dict2, **dict3}
print(f"Merged with unpacking: {merged_dict_unpacking}")
# Accessing nested dictionaries safely
user_data = {
'id': 101,
'profile': {
'name': 'Bob',
'contact': {
'email': '[email protected]',
'phone': '123-456-7890'
}
},
'preferences': {'theme': 'dark'}
}
# Safe access using .get()
username = user_data.get('profile', {}).get('name', 'N/A')
user_phone = user_data.get('profile', {}).get('contact', {}).get('phone', 'N/A')
non_existent_field = user_data.get('settings', {}).get('language', 'English')
print(f"Username: {username}")
print(f"User Phone: {user_phone}")
print(f"Non-existent field (default): {non_existent_field}")
# Example of deep merging (more complex, but common in web dev)
def deep_merge(d1, d2):
for k, v in d2.items():
if k in d1 and isinstance(d1[k], dict) and isinstance(v, dict):
d1[k] = deep_merge(d1[k], v)
else:
d1[k] = v
return d1
config1 = {'database': {'host': 'localhost', 'port': 5432}, 'logging': {'level': 'INFO'}}
config2 = {'database': {'port': 5433}, 'cache': {'enabled': True}}
merged_config = deep_merge(config1.copy(), config2) # Pass a copy to avoid modifying config1
print(f"Deep Merged Config: {merged_config}")
How it works: This snippet demonstrates two primary ways to merge dictionaries: `dict.update()` for in-place modification or combining multiple dictionaries, and the `**` unpacking operator for creating a new merged dictionary (Python 3.5+). It also showcases how to safely access deeply nested values using the `dict.get()` method with default return values, preventing `KeyError` exceptions when keys might be missing. A simple `deep_merge` function is included for handling nested dictionary updates.