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)
JavaScript
x
8
1
mylist = [
2
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
3
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
4
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
5
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
6
7
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
8
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
JavaScript
1
5
1
counts = collections.Counter()
2
for d in package2019:
3
counts.update(d.keys())
4
count_list = [{c: counts[c] for c in d} for d in mylist]
5
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
Advertisement
Answer
you can use len() and a generator:
JavaScript
1
2
1
len(tuple(d for d in my_list if d['Receiver'] == 'Mike'))
2
you can use len() and filter():
JavaScript
1
2
1
len(tuple(filter(lambda d: d['Receiver'] == 'Mike', my_list)))
2
you can use sum() and map():
JavaScript
1
2
1
sum(map(lambda d: d['Receiver'] == 'Mike', my_list))
2
this counts all the Mikes, if you want the Janes too, you have to add it to the condition.