使用collections.Counter()
instance,一些链接在一起:
from collections import Counter
from itertools import chain
counts = Counter(chain.from_iterable(e.keys() for e in d))
这保证了在你的输入列表中有多个键的字典进行正确计数。
演示:
>>> from collections import Counter
>>> from itertools import chain
>>> d = [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]
>>> Counter(chain.from_iterable(e.keys() for e in d))Counter({'pqr': 5, 'abc': 3, 'xyz': 1})
或与输入的词典多个键:
>>> d = [{"abc":"movies", 'xyz': 'music', 'pqr': 'music'}, {"abc": "sports", 'pqr': 'movies'}, {"abc": "music", 'pqr': 'sports'}, {"pqr":"news"}, {"pqr":"sports"}]
>>> Counter(chain.from_iterable(e.keys() for e in d)) Counter({'pqr': 5, 'abc': 3, 'xyz': 1})
甲Counter()
具有附加的,有益的功能,例如,该目录排序的元件,反向其计数.most_common()
method订购:
for key, count in counts.most_common():
print '{}: {}'.format(key, count)
# prints
# 5: pqr
# 3: abc
# 1: xyz
你的意思是你有字典的名单?还是它复制不正确? – thegrinner 2013-05-06 20:05:39
这不是一本字典,它至多是一个字典列表(它只包含一个键/值对) - 真的吗?这是什么样的数据结构?我猜它实际上是'[{“abc”:“电影”},...,对吧? – 2013-05-06 20:05:55
@TimPietzcker没错。对不起,代表性错误 – user1189851 2013-05-06 20:06:55