计算python字典中每个键的出现次数

计算python字典中每个键的出现次数

本文介绍了计算python字典中每个键的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的python字典对象:

I have a python dictionary object that looks somewhat like this:

[{"house": 4,  "sign": "Aquarius"},
 {"house": 2,  "sign": "Sagittarius"},
 {"house": 8,  "sign": "Gemini"},
 {"house": 3,  "sign": "Capricorn"},
 {"house": 2,  "sign": "Sagittarius"},
 {"house": 3,  "sign": "Capricorn"},
 {"house": 10, "sign": "Leo"},
 {"house": 4,  "sign": "Aquarius"},
 {"house": 10, "sign": "Leo"},
 {"house": 1,  "sign": "Scorpio"}]

现在,对于每个符号"键,我想计算每个值出现多少次.

Now for each 'sign' key, I'd like to count how many times each value occurs.

def predominant_sign(data):
    signs = [k['sign'] for k in data if k.get('sign')]
    print len(signs)

但是,这会打印出"sign"出现在字典中的次数,而不是获取sign的值并计算出现特定值的次数.

This however, prints number of times 'sign' appears in the dictionary, instead of getting the value of the sign and counting the number of times a particular value appears.

例如,我想看到的输出是:

For example, the output I'd like to see is:

Aquarius: 2
Sagittarius: 2
Gemini: 1
...

以此类推.我应该改变什么以获得期望的输出?

And so on. What should I change to get the desired output?

推荐答案

使用 collections.Counter 及其 most_common方法:

from collections import Counter
def predominant_sign(data):
    signs = Counter(k['sign'] for k in data if k.get('sign'))
    for sign, count in signs.most_common():
        print(sign, count)

这篇关于计算python字典中每个键的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 03:35