PYTHON
Merge Dictionaries with Custom Conflict Resolution
Merge two Python dictionaries, applying custom logic to resolve value conflicts for common keys, allowing for sophisticated data aggregation beyond simple overwriting.
def merge_dicts_custom_strategy(dict1, dict2):
merged = dict1.copy() # Start with a copy of dict1
for key, value in dict2.items():
if key in merged:
# Custom conflict resolution logic
if isinstance(merged[key], list) and isinstance(value, list):
merged[key].extend(value) # Extend lists
elif isinstance(merged[key], (int, float)) and isinstance(value, (int, float)):
merged[key] += value # Sum numbers
else:
merged[key] = value # Default: dict2's value overrides
else:
merged[key] = value # Key not in dict1, just add it
return merged
# Example Usage:
dict_a = {'id': 1, 'tags': ['python', 'web'], 'count': 5, 'name': 'Item A'}
dict_b = {'id': 2, 'tags': ['flask', 'web'], 'count': 3, 'name': 'Item B'}
dict_c = {'id': 1, 'tags': ['django'], 'count': 2, 'status': 'active'}
# Merging dict_a and dict_c with custom rules
result = merge_dicts_custom_strategy(dict_a, dict_c)
# Expected result: {'id': 1, 'tags': ['python', 'web', 'django'], 'count': 7, 'name': 'Item A', 'status': 'active'}
How it works: This function merges two dictionaries by iterating through the second dictionary. If a key exists in both, it applies custom logic: if both values are lists, they are extended; if both are numbers, they are summed. Otherwise, the second dictionary's value overwrites the first. New keys from the second dictionary are simply added. This is invaluable for aggregating configuration, user preferences, or data from multiple sources where simple overwriting isn't sufficient.