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