Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created April 13, 2024 21:59
Show Gist options
  • Save fancellu/4c72f86389bb3fc9810be976dd757927 to your computer and use it in GitHub Desktop.
Save fancellu/4c72f86389bb3fc9810be976dd757927 to your computer and use it in GitHub Desktop.
Python dictionary list adder
def add_dicts_list(dict_list):
"""
This function adds a list of dictionaries element-wise.
Args:
dict_list: A list of dictionaries with k->int elements.
Returns:
A new dictionary with the sum of the corresponding elements from all dictionaries in dict_list.
"""
result = {key: sum(d.get(key, 0) for d in dict_list) for key in set.union(*[set(d.keys()) for d in dict_list])}
return result
# Example usage
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 3, 'c': 4}
dict3 = {'a': 2, 'd': 1}
sum_dict = add_dicts_list([dict1, dict2, dict3])
print(sum_dict) # Output: {'a': 6, 'b': 2, 'c': 4, 'd': 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment