I have a python dictionary object that looks somewhat like this:
[{\"house\": 4, \"sign\": \"Aquarius\"},
{\"house\": 2, \"sign\": \"Sagittarius\"},
{\"h
Use collections.Counter and its most_common method:
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)
You can use collections.Counter module, with a simple generator expression, like this
>>> 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 signs
as keys and their number of occurrences as the values.
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.get
method, 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 0
instead.