简体   繁体   中英

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) ?!?)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM