-2

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#)?

halfer
  • 19,824
  • 17
  • 99
  • 186
CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • 1
    your list` is missing a closing double quote in `"place` and in `"time` making the syntax incorrect. – Sembei Norimaki Nov 21 '22 at 17:06
  • https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-and-checking-how-many-key-value-pairs-are-equal You might want to take a look at this. – Rahil Prakash Nov 21 '22 at 17:07
  • List comprehensions are faster than a standard loop as they (are likely) implemented in C...that is one option and your lists aren't complex so it would be easy to read – ViaTech Nov 21 '22 at 17:14
  • And there are extraneous colons that are incorrect. – Lenormju Nov 22 '22 at 10:14

1 Answers1

0

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"
  }
]
Lenormju
  • 4,078
  • 2
  • 8
  • 22