-1

I have two lists of dictionaries list_1 and list_2. I want to update each dictionary in list_2 with the proper value(s) from the corresponding dictionary from list_1 based on a match key values.

I am finding it difficult to iterate over dictionaries in a list. Any help would be appreciated.

INPUT:

list_1 = [
    {'time': '2022-02-22T19:36:48.343000Z', 'name': 'oracle1', 'qid': '100172', 'utep': 'UEXC00345345'}, 
    {'time': '2022-02-22T19:36:48.343000Z', 'name': 'oracle2', 'qid': '105134', 'utep': 'UEXC1231231'}
]

list_2 = [
    {'time': '2021-03-02T23:31:46.495993Z', 'server_id': '100172', 'name': 'apache1'}, 
    {'time': '2021-03-02T23:31:46.516669Z', 'server_id': '100178', 'name': 'apache2'}
]

My code so far:

for k in list1:
    for Q in list2:
        if (qid == server_id):
            list2.insert(list1[utep]
wovano
  • 4,543
  • 5
  • 22
  • 49
peter
  • 17
  • 5
  • 1
    Are you searching for [`zip()`](https://docs.python.org/3/library/functions.html#zip)? `[{**d1, **d2} for d1, d2 in zip(list1, list2)]` – Olvin Roght Mar 07 '22 at 20:33
  • I don't think this should have been closed as a `zip()` dupe. I think the questions is how to update a list of dictionaries based on a second list of dictionaries where there is a key match. – JonSG Mar 07 '22 at 21:02
  • 1
    @JonSG, I am not the one who closed it but I'd definitely vote to close it with "Need details of clarity" reason. – Olvin Roght Mar 07 '22 at 21:10

1 Answers1

1

I am not sure if this is what you want, but I think your code should be this:

for k in list1:
    for Q in list2:
        if k["qid"] == Q["server_id"]:
            Q["utep"] = k["utep"]
Rik Mulder
  • 245
  • 1
  • 9