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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30963408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:14:19  来源:igfitidea点击:

Count occurrences of each key in python dictionary

pythonpython-2.7dictionary

提问by Newtt

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

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

[{"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)

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

但是,这会打印字典中出现“符号”的次数,而不是获取 的值sign并计算特定值出现的次数。

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?

等等。我应该更改什么才能获得所需的输出?

采纳答案by vaultah

Use collections.Counterand its most_commonmethod:

用途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)

回答by thefourtheye

You can use collections.Countermodule, with a simple generator expression, like this

您可以使用collections.Counter带有简单生成器表达式的模块,如下所示

>>> from collections import Counter
>>> Counter(k['sign'] for k in data if k.get('sign'))
Counter({'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1}) 

This will give you a dictionary which has the signsas keys and their number of occurrences as the values.

这将为您提供一个字典,其中包含signs作为键及其出现次数作为值。



You can do the same with a normal dictionary, like this

你可以用普通的字典做同样的事情,像这样

>>> result = {}
>>> for k in data:
...     if 'sign' in k:
...         result[k['sign']] = result.get(k['sign'], 0) + 1
>>> result
{'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1}

The dictionary.getmethod, accepts a second parameter, which will be the default value to be returned if the key is not found in the dictionary. So, if the current sign is not in result, it will give 0instead.

dictionary.get方法接受第二个参数,如果在字典中找不到该键,该参数将是要返回的默认值。因此,如果当前符号不在 中result,它将0改为给出。