Count how many times a part of a key appears in a dictionary python

☆樱花仙子☆ 提交于 2019-12-25 02:19:33

问题


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

回答1:


>>> 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:


Use itertools.chain and a collections.Counter:

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

Alternatively:

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



回答3:


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



回答4:


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"



回答5:


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

Hope that sorts it.




回答6:


Using python 3.2

from collections import Counter
from itertools import chain  

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


来源:https://stackoverflow.com/questions/13447226/count-how-many-times-a-part-of-a-key-appears-in-a-dictionary-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!