Home > Software engineering >  python update each dict object in list
python update each dict object in list

Time:05-11

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 :

[{'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..

CodePudding user response:

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}, ...]

CodePudding user response:

Well, the main point is to update every element of the list1. You can use enumerate to traverse through the list.

for list in enumerate(list1):
    list[1].update(list2[list[0]])
print(list1)
  • Related