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!
>Solution :
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})