Home > other >  How to loop through two nested lists and add a value from one to the other if they share a common va
How to loop through two nested lists and add a value from one to the other if they share a common va

Time:03-21

Let me give an example. So I have List A and List B...

lista = [[87, 56, Soccer], [45, 56, Baseball], [86, 34, Basketball], [98, 27, Football]]
listb = [[Baseball, BASE], [Football, FOOT], [Basketball, BASK]]

And I want to create List C that looks like this...

listc = [[45, 56, Baseball, BASE], [86, 34, Basketball, BASK], [98, 27, Football, FOOT]]

Or the desired value can be appended to List A without a new list being created. Whichever works best.

CodePudding user response:

Probably the easiest way to do this is to convert listb into a dictionary, then you can include elements in listc from lista if the key (the third value) exists in the dictionary:

lista = [[87, 56, 'Soccer'], [45, 56, 'Baseball'], [86, 34, 'Basketball'], [98, 27, 'Football']]
listb = [['Baseball', 'BASE'], ['Football', 'FOOT'], ['Basketball', 'BASK']]
dictb = dict(listb)
listc = [ [*v, k, dictb.get(k) ] for [*v, k] in lista if k in dictb ]
listc

Output:

[[45, 56, 'Baseball', 'BASE'], [86, 34, 'Basketball', 'BASK'], [98, 27, 'Football', 'FOOT']]

CodePudding user response:

This should work, but it's not the best way to do it. You should use a dictionary instead of listb.

def find(elem_a, listb):
  for x in list_b:
    if elem_a == x[0]:
      return x[1]
  return False

listc = []
for sub_list in lista:
  a = find(sub_list[2], listb)
  if a:
    listc.append(sublist   [a])
  • Related