使用 python 2.6:
我有一个字典,其中每个键都包含一个值列表。
我想查看字典中的所有值,并计算每个值在所有键中出现的次数。
我一直在看 itervalues() 或
for value in dictionary.values():
首先,还有 .count() 函数,但我需要返回直方图。
例如:
print dictionary
会回来
{'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']}
我想告诉我一些事情:
{'spam' : 3, 'eggs' : 1, 'cheese': 2, 'goats' : 1}
请您参考如下方法:
from collections import Counter
d = {'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']}
c = Counter(sum(d.values(), []))
# or c = Counter(x for a in d.values() for x in a)
print c.most_common()
## [('spam', 3), ('cheese', 2), ('eggs', 1), ('goats', 1)]
对于 python 2.6 使用 this recipe .
