Search code examples
pythonpython-3.xlistnestednested-lists

How to merge 2 nested lists


I want to merge 2 lists:

list1 = ['a', ['b', ['c', ['lol', [{'s': '21'}]]]]]
list2 = ['a', ['f', ['d', [{'x': '22'}]]]]]

The expected result:

['a', ['b', ['c', ['lol', [{'s': '21'}]]]], ['f', ['d', [{'x': '22'}]]]]

I tried get by key, but I didn't get what I expected.


Solution

  • It is not clear to me how you intend to identify duplications at nested levels but at the first level, you could use a list comprehension to filter the items of the second list excluding those that are in the first one:

    list1 = ['a', ['b', ['c', ['lol', [{'s': '21'}]]]]]
    list2 = ['a', ['f', ['d', [{'x': '22'}]]]]
    
    list3 = list1 + [i for i in list2 if i not in list1 ]
    
    print(list3)
    ['a', ['b', ['c', ['lol', [{'s': '21'}]]]], ['f', ['d', [{'x': '22'}]]]]