Python: Better way to compare two elements within two nested dict / list

Viewed 36

Is there better way to compare two nested dict / list without using nested for loops. I'm trying to match the serial number of the devices from two different sources, and create a dictionary output to combine two data. Having two for loops works for me but I feel like there is a better way of doing this. In reality, list_one has 15000 records, list_two has 8000 records. I'm pretty sure, each record from list_one is looping through 8000 records in list_two to find the match so basically, it's checking 120,000,000 possibilities with the if statement.

list_one = [{'sn': '1234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '2234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '3234', 'model': 'Dell', 'last_checkin': '8/22/2022'}]

list_two = [['1234', 'user_a', '8/22/2022'], ['2234', 'user_b', '8/22/2022'], ['3234', 'user_c', '8/22/2022']]

result_list = []
for l in list_one:
  for t in list_two:
    if l['sn'] == t[0]:
      result = {'sn': l['sn'], 'user': t[1], 'check_in': l['last_checkin']}
      result_list.append(result)
1 Answers

You can try something like this:

list_one = [{'sn': '1234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '2234', 'model': 'Dell', 'last_checkin': '8/22/2022'}, {'sn': '3234', 'model': 'Dell', 'last_checkin': '8/22/2022'}]

list_two = [['1234', 'user_a', '8/22/2022'], ['2234', 'user_b', '8/22/2022'], ['3234', 'user_c', '8/22/2022']]

lam = lambda l1: None if len(x:= [{"sn": l1["sn"], "user": l2[1], "check_in": l1["last_checkin"]} for l2 in list_two if l2[0] == l1['sn']]) == 0 else x
result_list = map(lam, list_one)
print(*result_list)

I don't know if this works for you, but you can try something similar.

Related