CF84 CF84 - 1 month ago 7
Python Question

Python: use of Counter in a dictionary of lists

Given a dictionary of lists like this:

d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}


I want to be able to count how many times each individual value appears in all lists. In the example given, the intended outcome would be:

occurrences={0.1:4, 0.2:1, 1.1:1, 1.2:1, 2.1:1, 2.2:1}


I was thinking of using
Counter
in a line like this:

occurrences = Counter([k[0] for k in d.values()])


but the output is
Counter({0.1: 1, 1.1: 1, 2.1: 1})
, meaning that the previous line only counts the occurrences of the first element of each list.

How can I extend this count to all elements of all lists?

wim wim
Answer

Since you don't appear to care about the keys of the dict, you can just use a nested comprehension:

>>> Counter(v for sublist in d.values() for v in sublist)
Counter({0.1: 4, 0.2: 1, 1.1: 1, 1.2: 1, 2.1: 1, 2.2: 1})