Home > Software design >  Compare 2 lists and update the properties in python
Compare 2 lists and update the properties in python

Time:11-22

I have 2 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 where ever the name is marching, 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#).
ANy help is highly appreciated.

CodePudding user response:

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"
  }
]
  • Related