Snaaa
Snaaa

Reputation: 256

Counting values in a dictionary

I have a dictionary where the values are lists, and I would like to count how many times each item appears in the list associated with each key. For example: my_dict= {10:[23,24,23,23,24],11:[17,23,23,17,24]} would generate 10:(23:3,24:2),11:(17:2,23:2,24:1)

I have tried using

from collections import Counter
counts = Counter((k, v) for k, v in my_dict.items())
print(counts)

which I found here, but with no success, as the values are lists, so are unhashable. I have fiddled about with collections.Counter and the structure of the dictionary for a while now, but nothing seems to be working. All of the solutions I have found online have been for dictionaries with one value per key, and for duplicates in the whole dictionary, not per key.

Upvotes: 1

Views: 554

Answers (2)

Igor Chubin
Igor Chubin

Reputation: 64563

counts = {k:Counter(v) for (k,v) in my_dict.items()}

Upvotes: 0

jamylak
jamylak

Reputation: 133554

>>> from collections import Counter
>>> my_dict= {10:[23,24,23,23,24],11:[17,23,23,17,24]}
>>> {k: Counter(v) for k, v in my_dict.items()}
{10: Counter({23: 3, 24: 2}), 11: Counter({17: 2, 23: 2, 24: 1})}

Upvotes: 2

Related Questions