Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over a list of dictionaries and get value from previous dictionary

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading