Reputation: 6200
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?
Upvotes: 23
Views: 53315
Reputation: 557
def counter(my_list):
my_list = sorted(my_list)
first_val, *all_val = my_list
p_index = my_list.index(first_val)
my_counter = {}
for item in all_val:
c_index = my_list.index(item)
diff = abs(c_index-p_index)
p_index = c_index
my_counter[first_val] = diff
first_val = item
c_index = my_list.index(item)
diff = len(my_list) - c_index
my_counter[first_val] = diff
return my_counter
>>> counter([list(i.values())[1] for i in my_list])
{'Aquarius': 2,
'Capricorn': 2,
'Gemini': 1,
'Leo': 2,
'Sagittarius': 2,
'Scorpio': 1}
Upvotes: 0
Reputation: 239683
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.
Upvotes: 10
Reputation: 46603
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)
Upvotes: 23