Reputation: 793
Background
The following code works for adding 2 days to a date (e.g. 1/1/2000
becomes 1/3/2000
and is taken from Altering date in list of dictionary
import datetime
list_of_dic = [{'id': 'T1','type': 'LOCATION-OTHER','start': 142,'end': 148,'text': 'California'},
{'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
{'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'},
{'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
{'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/1/2000'}]
for i in list_of_dic: #Iterate list
if i["type"] == 'DATE': #Check 'type'
i["text"] = (datetime.datetime.strptime(i["text"], "%m/%d/%Y") + datetime.timedelta(days=2)).strftime("%m/%d/%Y") #Increment days.
print(list_of_dic)
Output
[{'id': 'T1', 'type': 'LOCATION-OTHER', 'start': 142, 'end': 148, 'text': 'California'},
{'id': 'T2', 'type': 'PHONE', 'start': 342, 'end': 352, 'text': '123456789'},
{'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '01/03/2000'},
{'id': 'T10', 'type': 'DOCTOR', 'start': 692, 'end': 701, 'text': 'Joe'},
{'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '05/03/2000'}]
Question
How would the code change if one wanted to save the output from print(list_of_dic)
in a new list called new_list_of_dic
?
Upvotes: 0
Views: 45
Reputation: 6476
Just use copy
?
new_list_of_dic = list_of_dic.copy()
Or if you want the string?
new_list_of_dic = str(list_of_dic)
Upvotes: 1