1

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?

dfadeeff
  • 81
  • 1
  • 8
  • 1
    Does this answer your question? [How do I merge two dictionaries in a single expression (taking union of dictionaries)?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona) – user_na Apr 19 '21 at 20:21
  • Not exactly, but it provides useful hints for similar problems. Thanks for the link! I guess my question has already been answered by now in the comments section. – dfadeeff Apr 19 '21 at 20:39

1 Answers1

1

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}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91