如何计算python字典中总值的频率?

时间:2017-05-02 01:34:26

标签: python dictionary count frequency

我觉得这是一个重复的问题。让我们说我有以下python字典:

dict = {"file1":["January", "April", "May", "December"], 
    "file2":["February", "March", "May", "December"], 
    "file3":["March", "October", "November", "December"]}

我想知道此词典dict中每个值的总频率,即

"December": 3
"May": 2
"March": 2
"January": 1
"February": 1
"April": 1
"October": 1 
"November": 1 

最终目标是创建一个直方图,所以我怀疑我会把它转换成一个熊猫系列。

这通常是怎么做的?

1 个答案:

答案 0 :(得分:2)

您可以使用Counter这是一个dict子类来计算可散列对象:

>>> d = {"file1": ["January", "April", "May", "December"], "file2": ["February", "March", "May", "December"],"file3": ["March", "October", "November", "December"]}
>>>
>>> from collections import Counter
>>> Counter(sum(d.values(),[]))

Counter({'December': 3, 'March': 2, 'May': 2, 'February': 1, 'October': 1, 'April': 1, 'January': 1, 'November': 1})