I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to that key in each of the dictionaries. (For example, the value for the key 'apple' in the combined dictionary will be the sum of the value of 'apple' in the first, plus the sum of the value of 'apple' in the second, etc.)
I have the following, but it's rather cumbersome and takes ages to execute. Is there a simpler way to achieve the same result?
comb_dict = {}
for dictionary in list_dictionaries:
for key in dictionary:
comb_dict.setdefault(key, 0)
comb_dict[key] += dictionary[key]
return comb_dict