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)
?!?)
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.
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 elements in a Nested Dictionary, we can use the Built-in function len().
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.
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
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