Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a list of dictionaries (abbreviated).

my_list = [{ 'id':1, 'val':123 }, {'id':2, 'val':456 }, {'id':2, 'val':789 }]

How can I count the occurrences of dictionaries with a specified value for a particular key (in this case 'id')? Is there a way to leverage count (my_list.count('id' = 1) ?!?)

like image 361
Jamie Avatar asked Sep 22 '13 05:09

Jamie


People also ask

How do you count occurrences of an item in a list?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How do you count occurrences of values in a dictionary Python?

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.

How do you count elements in a dictionary?

To count elements in a Nested Dictionary, we can use the Built-in function len().


2 Answers

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.

like image 116
Ray Toal Avatar answered Sep 22 '22 22:09

Ray Toal


I like @Ray's answer. Another cool trick is to use collections.Counter.

from collections import Counter

c = Counter( item for dct in my_list for item in dct.items() )
c
=> Counter({('id', 2): 2, ('val', 123): 1, ('id', 1): 1, ('val', 456): 1, ('val', 789): 1})

c[('id', 2)]
=> 2
c[('id', 1)]
=> 1
c[('id', 20)]
=> 0

This solution is particularly good if you need to count multiple keys/values.

If you only care about a particular key, you can do:

k = 'id'
id_counter = Counter( dct.get(k) for dct in my_list )
id_counter
=> Counter({2: 2, 1: 1})
id_counter[2]
=> 2
like image 38
shx2 Avatar answered Sep 23 '22 22:09

shx2