Nikoloz Mamisashvili Nikoloz Mamisashvili - 1 month ago 9
Python Question

Replace values in list of lists

Python 3. Windows 10.

I have hierarchical list and I want to change their values with the values specified.

for example: I have hierarchical list

l = [[[0, 4], 1], [2, 3], 5]]

and I have a dictionary

{0: 'da-1.txt',
1: 'da-2.txt',
2: 'en-1.txt',
3: 'en-2.txt',
4: 'it-1.txt',
5: 'it-2.txt'}

And I want to replace values of list with the values of dictionary correspondingly without breaking the list hierarchy structure.
Output should be like this:

l = [[['da-1.txt', 'it-1.txt'], 'da-2.txt'], ['en-1.txt', 'en-2.txt], 'it-2.txt']


You could go over the list and for each element check if it's a list. If it isn't, replace it with the corresponding element of the dictionary if it exists. If it is, apply the same algorithm recursively:

def rec_replace(l, d):
    for i in range(len(l)):
        if isinstance(l[i], list):
            rec_replace(l[i], d)
        else :
            l[i] = d.get(l[i], l[i])

This implementation is of an in-place replacement of the list's elements. Alternatively, a similar approach could be used to return a new list instead.