Home > Software engineering >  How to merge 2 lists of dictionaries together and at the same time group by the same key
How to merge 2 lists of dictionaries together and at the same time group by the same key

Time:03-20

My two dictionaries look like this

list1 = [{'time': '2020', 'name': 'one', 'address': '15423'},{'time': '2021', 'name': 'two', 'address': '8548305'}]
list2 = [{'to': '15423', 'value': '5'}, {'to': '8548305', 'value': '90'}, {'to': '123', 'value': '5'}]

I want my final list of dictionaries to look like this. Also, I don't want to consider dictionary if it doesn't have a match from another list of dictionaries

list3 = [{'time': '2020', 'name': 'one', 'address': '15423', 'value': '5'}, {'time': '2021', 'name': 'two', 'address': '8548305', 'value': '90'}]

Here is what I tried

[lst1.update(lst2) for lst1, lst2 in zip(list1, list2)]

But I don't know how can I group by address. Appreciate your help

CodePudding user response:

You are on the right track. You can do something like:

[{**lst1 , **lst2} for lst1 in list1 for lst2 in list2 if lst1["address"] == lst2["address"]]

Output

[{'address': '15423', 'name': 'one', 'time': '2020', 'value': '5'},
 {'address': '8548305', 'name': 'two', 'time': '2021', 'value': '90'}]

Note that, list comprehension might not be the best idea, since it lacks break and continue commands. Maybe it's more efficient to something like:

for index,lst1 in enumerate(list1):
  for lst2 in list2:
    if lst2["address"] == lst1["address"]:
      list1[index]["value"] = lst2["value"]
      break
list1

Output

[{'address': '15423', 'name': 'one', 'time': '2020', 'value': '5'},
 {'address': '8548305', 'name': 'two', 'time': '2021', 'value': '90'}]
  • Related