Python: using a counter in a list dictionary

Given the dictionary of such lists: 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 given example, the expected result:

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

I thought of using Counterin a line like this:

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

but the conclusion Counter({0.1: 1, 1.1: 1, 2.1: 1}), which means that the previous line only considers occurrences of the first element of each list.

How to increase this score to all elements of all lists?

+4
source share
2 answers

Since you don't seem to care about dict keys, you can just use the understanding:

>>> 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})
+5
source

. itertools.chain.from_iterable, :

from collections import Counter
from itertools import chain

d={0:[0.1,0.2,0.1], 1:[1.1,1.2,0.1], 2:[2.1,2.2,0.1]}
c = Counter(chain.from_iterable(d.values()))
print(c)
# Counter({0.1: 4, 0.2: 1, 1.2: 1, 2.2: 1, 1.1: 1, 2.1: 1})
+3

Source: https://habr.com/ru/post/1658832/


All Articles