Advertisements
I have a list of dictionaries:
history_changes = [
{'userName': 'recg', 'modificationDate': '2022-07-14T04:01:39+00:00', 'changeComment': 'more details about L2'},
{'userName': 'artf', 'modificationDate': '2022-07-15T04:01:39+00:00', 'changeComment': 'more details about L1'},
{'username': 'zrt', 'modificationDate': '2022-07-16T04:01:39+00:00', 'changeComment': 'more details about L3'}]
I’m iterating over it and trying to insert data in a database.
for record in history_changes[1:]:
comment = record['changeComment']
to_time = record['modificationDate']
I also need the "start_time" information which is the ‘modificationDate’ from the previous dictionary.
Expected output:
comment = 'more details about L1'
start_time = '2022-07-14T04:01:39+00:00'
to_time = '2022-07-15T04:01:39+00:00'
comment = 'more details about L3'
start_time = '2022-07-15T04:01:39+00:00'
to_time = '2022-07-16T04:01:39+00:00'
How can I get the 'modificationDate'
from the previous dictionary when iterating over the list?
>Solution :
history_changes = [
{'userName': 'recg', 'modificationDate': '2022-07-14T04:01:39+00:00', 'changeComment': 'more details about L2'},
{'userName': 'artf', 'modificationDate': '2022-07-15T04:01:39+00:00', 'changeComment': 'more details about L1'},
{'username': 'zrt', 'modificationDate': '2022-07-16T04:01:39+00:00', 'changeComment': 'more details about L3'}]
for x in range(1,len(history_changes)): # see here I am starting from 1 index
print(history_changes[x]['changeComment'])
print(history_changes[x-1]['modificationDate'])
print(history_changes[x]['modificationDate'])
#output
more details about L1
2022-07-14T04:01:39+00:00
2022-07-15T04:01:39+00:00
more details about L3
2022-07-15T04:01:39+00:00
2022-07-16T04:01:39+00:00
If you want to store these value then:
comment=[]
start_time=[]
to_time=[]
for x in range(1,len(history_changes)):
comment.append(history_changes[x]['changeComment'])
start_time.append(history_changes[x-1]['modificationDate'])
to_time.append(history_changes[x]['modificationDate'])