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)