Home > Blockchain >  Count the existence number of a key in a list of dictionary
Count the existence number of a key in a list of dictionary

Time:02-10

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

CodePudding user response:

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.

CodePudding user response:

You could use a list comprehension to build a list of receivers. Then pass that list to collections.Counter to get the counts of how many times each receiver appears in mylist:

from collections import Counter
receivers = [d['Receiver'] for d in mylist]
counts = Counter(receivers)

Output:

Counter({'Mike': 2, 'Jane': 2, 'Jack': 1})
  • Related