简体   繁体   中英

Add a key/value pair(With caculation) in a list of dictionaries

I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines)

mysheet=[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike},{'StartDate': '2021-11-02', 'ID': 15673, 'Receiver': Jane}, ... {'StartDate': '2021-10-10', 'ID': 34653, 'Receiver': Jack}]

I want to add a key/value pair to this list, and the value will use the values from the former cells with a function. For example, I want to calculate how many days from today,so my list will show as this:

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

Please help:)

You can use

mysheetnew = []
for item in mysheet:
    temp = item.copy()
    temp["keyname"] = value
    mysheetnew.append(temp)

and instead of values , you can put func(temp["date"]) or else. Hope it helped.

Edit: More precisely

import datetime

mysheetnew = []
for item in mysheet:
    temp = item.copy()
    timediff = datetime.datetime.now() - datetime.datetime.strptime(temp["StartDate"], "%Y-%m-%d")
    temp["Days"] = timediff.days
    mysheetnew.append(temp)

This makes use of the datetime module to manipulate dates and to have the difference between two dates.

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