Reputation: 793
Background
I have a list of dictionary values
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'}]
Goal
1) Locate all 'type': 'DATE'
in list_of_dict
2) Add 2
days to the corresponding 'text: 'value'
Example
{'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/1/2000'}
will become
{'id': 'T3', 'type': 'DATE', 'start': 679, 'end': 687, 'text': '1/3/2000'}
Desired Output
desired_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/3/2000'},
{'id': 'T10','type': 'DOCTOR','start': 692,'end': 701,'text': 'Joe'},
{'id': 'T11', 'type': 'DATE', 'start': 702, 'end': 710, 'text': '5/3/2000'}]
Upvotes: 0
Views: 50
Reputation: 82765
Use datetime
module
Ex:
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:
[{'end': 148,
'id': 'T1',
'start': 142,
'text': 'California',
'type': 'LOCATION-OTHER'},
{'end': 352, 'id': 'T2', 'start': 342, 'text': '123456789', 'type': 'PHONE'},
{'end': 687, 'id': 'T3', 'start': 679, 'text': '01/03/2000', 'type': 'DATE'},
{'end': 701, 'id': 'T10', 'start': 692, 'text': 'Joe', 'type': 'DOCTOR'},
{'end': 710, 'id': 'T11', 'start': 702, 'text': '05/03/2000', 'type': 'DATE'}]
datetime.timedelta(days=N)
--> to increment daysdatetime.datetime.strptime
--> to convert string to datetime objectstrftime
--> to convert datetime object to stringUpvotes: 1