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?
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With