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?
If you want to count the occurrences of each value in a Python dictionary, you can use the collections. Counter() function on the dictionary values. It returns the number of times each value occurs in the dictionary.
To count the values by key in a Python dictionary, you can use comprehension to loop over the dictionary items, and then count the number of items for a given key with the Python len() function. In Python, dictionaries are a collection of key/value pairs separated by commas.
method 3: Use len() function to count the number of keys in a dictionary. The len() function is used to find the length of objects. It returns the total number of items. In dictionaries, the items are stored in the form of key-value pairs which means that the total number of items and keys are equal.
By using the counter() method we can easily count the duplicate values in the dictionary.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With