0

I have the following dictionary and i want to count how many times keys appear, dictionary is very big.

a = { (1,2):3, (1,3):5, (2,1):6 }

and I want this result

1: 3 times
2: 2 times
3: 1 time
Aesthete
  • 17,984
  • 6
  • 34
  • 44
Mike B
  • 1,432
  • 1
  • 14
  • 23

6 Answers6

9

Use itertools.chain and a collections.Counter:

collections.Counter(itertools.chain(*a.keys()))

Alternatively:

collections.Counter(itertools.chain.from_iterable(a.keys()))
mgilson
  • 283,004
  • 58
  • 591
  • 667
5
>>> from collections import Counter
>>> a = { (1,2):3, (1,3):5, (2,1):6 }
>>> 
>>> Counter(j for k in a for j in k)
Counter({1: 3, 2: 2, 3: 1})
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
  • Every time I write this particular comprehension (flattening one) I need to stop for a while and think about the order of `j`s, `k`s and `a`s :) Still, very nice solution. – cji Nov 19 '12 at 03:52
4

Use itertools and collections.defaultdict

In [43]: a={(1,2):3,(1,3):5,(2,1):6}

In [44]: counts = collections.defaultdict(int)

In [45]: for k in itertools.chain.from_iterable(a.keys()):
   ....:     counts[k] += 1
   ....:     

In [46]: for k in counts:
    print k, ": %d times" %counts[k]
   ....:     
1 : 3 times
2 : 2 times
3 : 1 times
inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
0

First, this is not a code-writing service. Try writing some first, and then asking a question about it.

Second, as a freebie, in Python:

import collections
s = collections.defaultdict(int)
for j, k in a.keys():
   s[j] += 1
   s[k] += 1
for x in s.keys():
   print x + ": " + s[x] + " times"
jdotjdot
  • 15,178
  • 11
  • 63
  • 112
0
from collections import Counter
items = Counter(val[2] for val in dic.values())

Hope that sorts it.

hd1
  • 32,598
  • 5
  • 75
  • 87
0

Using python 3.2

from collections import Counter
from itertools import chain  

res = Counter(list(chain(*a)))
Shawn Chin
  • 79,172
  • 18
  • 156
  • 188
raton
  • 410
  • 5
  • 14