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

Time:02-05

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 :)

CodePudding user response:

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.

  •  Tags:  
  • Related