Reputation: 2840
I have a defaultdict
, then converted to a dictionary. Now I am looking for a way to count the items grouped by value. What i mean is:
dict = {1: [103], 2: [9], 3: [3, 4], 4: [103, 106], 10: [3, 4], 11: [1, 9], 28: [1]}
for key in dict.items():
print key
(1, [103])
(2, [9])
(3, [3, 4])
(4, [103, 106])
(10, [3, 4])
(11, [1, 9])
(28, [1])
item : total
{4 : 2, 106 : 1} ...
How can i do that?
Upvotes: 2
Views: 5990
Reputation: 514
m_dict = dict
n = {}
for k, v in m_dict.iteritems():
for j in v:
n[j] = (n[j] + 1 if n.get(j) != None else 1)
print n
Result:
{1: 2, 3: 2, 4: 2, 9: 2, 103: 2, 106: 1}
Or:
m_dict = dict
n = sum([v for k,v in m_dict.iteritems()], [])
c = {j : n.count(j) for j in n}
print c
Result:
{1: 2, 3: 2, 4: 2, 9: 2, 103: 2, 106: 1}
Upvotes: 0
Reputation: 239653
You can use collections.Counter
to count the number of occurrences of each element in the values lists, like this
>>> from collections import Counter
>>> Counter(value for values in d.itervalues() for value in values)
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
Counter
is a subclass of dictionary only. So, you can use it just like any other dictionary
The flattening of the values can be done with itertools.chain.from_iterable
, like this
>>> from collections import Counter
>>> from itertools import chain
>>> Counter(chain.from_iterable(d.itervalues()))
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
Upvotes: 8
Reputation: 10819
This is another way to do it without using anything but the basics.
d = {1: [103], 2: [9], 3: [3, 4], 4: [103, 106], 10: [3, 4], 11: [1, 9], 28: [1]}
answer = {} # store the counts here
for key in d:
for value in d[key]:
if value in answer:
# if the key is already in the answer
answer[value] += 1
else:
# if the key has never been counted before
# then add it to the answer and set its value to 1
answer.update({value:1})
for key in answer:
print key, answer[key]
It prints:
1 2
3 2
4 2
103 2
9 2
106 1
Upvotes: 0