Optimal code to check and append an item in a list if present in a list of dictionaries

Viewed 49

These are my inputs, pretty-printed for better readability

input1 = [{
    "ID": "1",
    "SequenceNum": 1
   },
   {
    "ID": "2",
    "SequenceNum": 2
   },
   {
    "ID": "3",
    "SequenceNum": 3
   },
   {
    "ID": "4",
    "SequenceNum": 4
   }]
input2 = ['4', '1']

The values contained in input2 are basically the values of the 'ID' key seen in input1

The output will be a list of dictionaries where input1[index]['ID'] == input2[index_element].

Expected output -> [{"ID": "4","SequenceNum": 4},{"ID": "1","SequenceNum": 1}]

I have solved this using the following lines of code:

match_list = []

for idx,val in enumerate(input1):
    match_list.append(val['ID'])

return_list = []

for idx,val in enumerate(input2):
    if val in match_list:
        get_idx = match_list.index(val)
        return_list.append(input1[get_idx])

While it works it doesn't feel like the most optimal nor the cleanest way to write code. I apologize for the basic question, I am not a very experienced programmer.

1 Answers

IIUC, you could do:

s = set(input2)
res = [d for d in input1 if d["ID"] in s]
print(res)

Output

[{'ID': '1', 'SequenceNum': 1}, {'ID': '4', 'SequenceNum': 4}]

This has an expected linear complexity.

If the order with respect to input2 needs to be kept, you could do:

lookup = {d["ID"]: d for d in input1}
res = [lookup[i] for i in input2 if i in lookup]
print(res)

This also has an expected linear complexity.

Related