Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
FaCoffee Avatar asked Jan 05 '23 04:01

FaCoffee


1 Answers

Since you don't appear to care about the keys of the dict, you can just use a 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})
like image 109
wim Avatar answered Jan 14 '23 04:01

wim