Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count the existence number of a key in a list of dictionary

I used gspread and pandas to convert my google sheet into a list of dictionaries. The example list is shown as follows: (It’s a very long list, so I only list a few lines)

mylist = [
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65}, 
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
... 
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]

I want to count the number of the existence of some keys, for example Mike and Jane in the Receiver field. I tried the following to count the total number of the rows, and I think I may use a similar code

counts = collections.Counter()
for d in package2019:
    counts.update(d.keys())
count_list = [{c: counts[c] for c in d} for d in mylist]

I just don’t know how should I count the number of existence for some keys. I’m new to python and I searched anywhere online with no luck

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use len() and a generator:

len(tuple(d for d in my_list if d['Receiver'] == 'Mike'))

you can use len() and filter():

len(tuple(filter(lambda d: d['Receiver'] == 'Mike', my_list)))

you can use sum() and map():

sum(map(lambda d: d['Receiver'] == 'Mike', my_list))

this counts all the Mikes, if you want the Janes too, you have to add it to the condition.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading