Skip to content
Advertisement

How to replace Python list item by multiple items?

input_list = [[0], 'h1'] # contain an arbitrary number of 'h1' in arbitrary indices
input_keys = {'h1':[[1],[1]]} # all key values are lists
# to implement
replace(input_list, input_keys) -> [[0], [1],[1] ]

How to replace element 'h1' from input_list by multiple elements from input_keys['h1']?

I have tried:

#[[0], [1, 1]]
list(map(lambda x: x if not isinstance(x, str) else list(itertools.chain(*input_keys[x])), input_list))
    
#[[0], [[1], [1]]]
list(map(lambda x: x if not isinstance(x, str) else input_keys[x], input_list))

Advertisement

Answer

A for loop will do the job.

output_list = []
for item in input_list:
   if str(item) in input_keys:
       output_list.extend(input_keys[item])
   else:
       output_list.append(item)

Note that I’m converting lists in the input_list into strings in order to check that they’re in the dictionary of input_keys.

Advertisement