python统计表中单词及其出现的次数 字典形式输出_计算python字典中每个键的出现次数...

1586010002-jmsa.png

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)

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?

解决方案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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值