计算密钥的一部分出现在字典python中的次数

时间:2012-11-19 03:23:52

标签: python list dictionary key tuples

我有以下字典,我想计算键出现的次数,字典非常大。

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

我想要这个结果

1: 3 times
2: 2 times
3: 1 time

6 个答案:

答案 0 :(得分:9)

使用itertools.chaincollections.Counter

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

可替换地:

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

答案 1 :(得分: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})

答案 2 :(得分:4)

使用itertoolscollections.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

答案 3 :(得分:0)

首先,这不是代码编写服务。先尝试写一些,然后问一个问题。

其次,作为免费赠品,在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"

答案 4 :(得分:0)

from collections import Counter
items = Counter(val[2] for val in dic.values())

希望对其进行排序。

答案 5 :(得分:0)

使用python 3.2

from collections import Counter
from itertools import chain  

res = Counter(list(chain(*a)))