简体   繁体   中英

How to tally the frequency of total values in a python dictionary?

I feel like this is a duplicate question. Let's say I have the following python dictionary:

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

I would like to know the total frequency of each value in this dictionary dict , ie

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

The end goal is to create a histogram, so I suspect I will convert this into a pandas Series.

How is this normally done?

You can use Counter which is a dict subclass for counting hashable objects :

>>> 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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM