Compare two lists and update the properties in Python

Question:

I have two lists in Python something similar.

list1 = [
    {"name": "sample1",
     "place": "sampleplace1",
     "value": "",
     "time": "sampletime"
     },
    {"name": "sample2",
     "place": "sampleplace2",
     "value": "",
     "time": "sampletime2"
     }
]

list2 = [
    {"name": "sample1",
     "value": "10"

     },
    {"name": "sample2",
     "value": "20"
     }
]

I need to compare both the lists and whereever the name is matching, I need to update the value property in list1. I did by running a for loop on list1, get the matching list object from list2 for each list1 object and update the value.

I’m just wondering, is there a way to do this without running a for loop (something like Linq in C#)?

Asked By: CrazyCoder

||

Answers:

Sadly, Python does not have the same abilities as LINQ.
If you don’t want to explicitly use a function there is map, but it uses a loop under the hood, as LINQ does.

You need for loops, like in :

list1 = [
    {"name": "sample1",
     "place": "sampleplace1",
     "value": "",
     "time": "sampletime"
     },
    {"name": "sample2",
     "place": "sampleplace2",
     "value": "",
     "time": "sampletime2"
     }
]

list2 = [
    {"name": "sample1",
     "value": "10"

     },
    {"name": "sample2",
     "value": "20"
     }
]

for elem1 in list1:
    for elem2 in list2:
        if elem1["name"] == elem2["name"]:
            # match ! we replace the value
            elem1["value"] = elem2["value"]
            break  # and stop searching
    else:
        print(f"no match in list2 for {elem1['name']=}")

# just for displaying the result
import json
print(json.dumps(list1, indent=2))
[
  {
    "name": "sample1",
    "place": "sampleplace1",
    "value": "10",
    "time": "sampletime"
  },
  {
    "name": "sample2",
    "place": "sampleplace2",
    "value": "20",
    "time": "sampletime2"
  }
]
Answered By: Lenormju
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.