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

python update each dict object in list

i have a issue in python

Now i have two list, i’d like to update every single dict in my list. how can i do ?
here is my two list

list1 = [{'x': '2022-04-29 07:53:34'}, {'x': '2022-04-29 07:56:00'}, {'x': '2022-04-29 09:07:00'}, {'x': '2022-04-29 09:12:00'}, {'x': '2022-04-29 09:12:07'}, {'x': '2022-04-29 09:35:40'}, {'x': '2022-04-29 09:39:02'}, {'x': '2022-05-04 02:17:00'}, {'x': '2022-05-04 05:59:41'}, {'x': '2022-05-05 10:04:14'}, {'x': '2022-05-06 05:44:17'}]

list2 = [{'y': 0}, {'y': 1}, {'y': 2}, {'y': 3}, {'y': 4}, {'y': 5}, {'y': 6}, {'y': 7}, {'y': 8}, {'y': 9}, {'y': 10}] 

this two list length is total equal
and the result need to :

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

[{'x': '2022-04-29 07:53:34','y': 0},{x': '2022-04-29 07:56:00','y': 1}...]

is there any one can do me a favor plz..

>Solution :

Try this:

for i in range(len(list1)):
        list1[i].update(list2[i])
        
print(list1)

Or if you don’t want list1 to be modified, make a copy first:

import copy

result = copy.deepcopy(list1)
for i in range(len(result)):
    result[i].update(list2[i])
print(result)

Output:

[{'x': '2022-04-29 07:53:34', 'y': 0}, {'x': '2022-04-29 07:56:00', 'y': 1}, ...]
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