Carla
Carla

Reputation: 3390

Python: How to aggregate and count identical values in a Dictionary

I'm using a defaultdict from Python's collections:

from collections import defaultdict
data = defaultdict(list)

Within the dictionary I have a set of key/list. Example:

{1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]})

I'm looking for a way to count how many times each list (identical order and content) is found in the dictionary. Basically, I need to aggregate each list with a counter. For example, the combination [1, 6, 3, 4, 5] is found 2 times. Is there any helper class/function that can do it? Other than that, I'd just create a double for loop across the dictionary. Thanks!

Upvotes: 0

Views: 411

Answers (3)

Nikolaj Š.
Nikolaj Š.

Reputation: 1996

Use collections.Counter

>>> from collections import Counter
>>> d = {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]}
>>> print(Counter(tuple(l) for l in d.values())
Counter({(1, 6, 3, 4, 5): 2, (1, 3, 2, 4, 5): 1})

You'll have to convert your lists to tuples, because Counters can't count unhashable (mutable) types.

Upvotes: 1

Rabinzel
Rabinzel

Reputation: 7923

Try this:

from collections import Counter
data = defaultdict(list, {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]})
c = Counter(map(tuple, data.values()))

print(c)

Counter({(1, 6, 3, 4, 5): 2, (1, 3, 2, 4, 5): 1})

Upvotes: 1

Ayyoub ESSADEQ
Ayyoub ESSADEQ

Reputation: 788

H = {1: [1, 6, 3, 4, 5], 2: [1, 3, 2, 4, 5], 3: [1, 6, 3, 4, 5]}
occurences = dict()
for i in H.keys() :
    k = 0
    for j in H.keys():
        if H[j] == H[i] :
            k += 1 
    if i not in occurences.keys():
        occurences[i] = k

Upvotes: 1

Related Questions