How to Count Occurrences of Key in List of Dictionaries

How to count occurrences of specific dict key in list of dicts

You could extract it, put it into a list, and calculate the list's length.

key_artists = [k['artist'] for k in entries if k.get('artist')]
len(key_artists)

Edit: using a generator expression might be better if your data is big:

key_artists = (1 for k in entries if k.get('artist'))
sum(key_artists)

2nd Edit:

for a specific artist, you would replace if k.get('artist') with if k.get('artist') == artist_pick

3rd Edit: you could loop as well, if you're not comfortable with comprehensions or generators, or if you feel that enhances code readability

n = 0  # number of artists

for k in entries:
n += 1 if k.get('artist') == artist_pick else 0

How to count occurrences of key in list of dictionaries

You can use list comprehension.

data = [{'a':1, 'b':1}, {'a':1, 'c':1}, {'b':1, 'c':1}, {'a':1, 'c':1}, {'a':1, 'd':1}]
sum([1 for d in data if 'a' in d])

Explanation:
First take the dictionary object from list data, check if key 'a' is present in the dictionary or not, if present, add 1 to the list. Then sum the new list.

check and count occurrence of particular key in list of dictionaries in python

You can do it with standard dicts:

result = {"active":{}, "inactive" ={}}
for i in data:
result.get(i.get("status"))[i.get("gender")] = result.get(i.get("status")).get(i.get("gender"),0)+1

How can I count the occurrences of an item in a list of dictionaries?

How about

sum(1 for d in my_list if d.get('id') == the_value_you_are_interested_in)

>>> my_list = [{ 'id':1, 'val':123 }, {'id':2, 'val':456 }, {'id':2, 'val':789 }]
>>> sum(1 for d in my_list if d.get('id') == 1)
1
>>> sum(1 for d in my_list if d.get('id') == 2)
2
>>> sum(1 for d in my_list if d.get('id') == 20)
0

Note the use of the generator rather than a list of 1s. This is a pretty established technique and probably appears on several Stack Overflow questions.

I don't see any way to leverage list.count(x) since this method counts the number of occurrences of x, which in your case would be complete dictionaries. Python does have a filter method, but comprehensions are much preferred.

How can I count occurrences of values in a list of dicts?

Given the result you've got so far...

>>> result = {'LARCENY' : 3, 'BURGLARY' : 2, 'ROBBERY - STREET' : 3}
>>> result = [{k:v} for k,v in result.items()]
>>> result
[{'BURGLARY': 2}, {'LARCENY': 3}, {'ROBBERY - STREET': 3}]

count number of occurrences in list by dict with key and value

You need them all to be at least as large. That means that you have to complete the loop before you can return success. Any failure means that you can return immediately.

for k, v in expected.items():
if results.count(k) < v:
return False

return True

Or, use the all function to put this into a single line:

return all(results.count(k) >= v for k, v in expected.items() )

How to make dictionary for number of occurrences in a list

You can do it in 2 steps, first create a list of lengths of individual items and them create a dictionary from the count list.

c = [len(item) for item in x]
d = {item:c.count(item) for item in c}

Count Occurrences of a Value in a List of Dictionaries

You can use collections.Counter and a generator expression to count how many times each country appears in the list. After that, you can use the most_common method to get the one that appears the most. The code will look like this:

from collections import Counter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]

[(country, _)] = Counter(x['country'] for x in aList).most_common(1)

print(country)
# Output: japan

Below is a demonstration of what each part does:

>>> from collections import Counter
>>> aList = [{'country': 'japan', 'city': 'tokyo', 'year': '1995'}, {'country': 'japan', 'city': 'hiroshima', 'year': '2005'}, {'country': 'norway', 'city': 'oslo', 'year': '2005'}]
>>> # Get all of the country names
>>> [x['country'] for x in aList]
['japan', 'japan', 'norway']
>>> # Total the names
>>> Counter(x['country'] for x in aList)
Counter({'japan': 2, 'norway': 1})
>>> # Get the most common country
>>> Counter(x['country'] for x in aList).most_common(1)
[('japan', 2)]
>>> # Use iterable unpacking to extract the country name
>>> [(country, _)] = Counter(x['country'] for x in aList).most_common(1)
>>> print(country)
japan
>>>


Related Topics



Leave a reply



Submit