Reputation: 71
There is an object, lets call it instance_list that contains a dictionary with a word and its occurence (called feature_counts). I would like to combine all of those dictionaries into one. So far, I have created a list comprehension like this
print("List:",[inst.feature_counts.items() for inst in self.instance_list])
and got the following list:
[dict_items([('deal', 1), ('lottery', 3)]), dict_items([('lottery', 2)]), dict_items([('deal', 1)]), dict_items([('green', 1), ('eggs', 1)])]
Expected output is this one:
{'deal':2,'lottery':5,'green':1,'eggs':1}
How do I transform my list comprehension into the final dict?
Upvotes: 0
Views: 273
Reputation: 195543
If your self.instance_list
is list of dictionaries, you can do:
out = {}
for inst in self.instance_list:
for k, v in inst.items():
out.setdefault(k, 0)
out[k] += v
print(out)
Prints:
{'deal': 2, 'lottery': 5, 'green': 1, 'eggs': 1}
Upvotes: 1