I am trying to modify a nested list_x based on matching elements found in a second nested list_y and replace the element with the item from list_2:
list_x = [['Light_1', 'CC', 'AA'], ['Light_2', 'BB'], ['Light_3', 'DD', 'AA']]
list_y = [['AA', 'ON'], ['BB', 'ON'], ['DD', 'OFF'], ['CC', 'ON'], ['EE', 'ON']]
So the aim is to end up with a list_x looking like:
list_x = [['Light_1', ['CC', 'ON'], ['AA', 'ON']], ['Light_2', ['BB', 'ON']], ['Light_3', ['DD', 'OFF'], ['AA', 'ON']]]
My code so far has only gotten me this:
for n, i in enumerate(list_x):
if i==list_y:
list_x[n]=list_y
list_x
[['Light_1', 'CC', 'AA'], ['Light_2', 'BB'], ['Light_3', 'DD', 'AA']]
Can someone please help find what's missing from my code to get the desired result?
Many thanks
I would first create a dictionary for the second list, so you don't have to search through that list every time you need a match with a key like "AA", "BB", ...etc, but can look it up faster in a dictionary:
dict_y = { key: value for key, value in list_y }
Then, map the first list to your desired output, making use of that dict:
result = [[light, [[key, dict_y[key]] for key in keys]] for light, *keys in list_x]