Maybe not the most elegant way, but this seems to work:
First, we turn the list of lists into a dictionary using a defaultdict
of defaultdicts
of defaultdicts
, aka infinitedict
myList = [['ItemB','ItemZ'],['ItemB','ItemP'],['ItemB','ItemJ','Item6'],['ItemB','ItemJ','Item5']]
from collections import defaultdict
infinitedict = lambda: defaultdict(infinitedict)
dictionary = infinitedict()
for item in myList:
d = dictionary
for i in item:
d = d[i]
Now, we can use a recursive function to turn that dictionary back into a tree-styled list:
def to_list(d):
lst = []
for i in d:
lst.append(i)
if d[i]:
lst.append(to_list(d[i]))
return lst
The output is a bit different from your expected output, but this seems to make more sense to me:
>>> print(to_list(dictionary))
['ItemB', ['ItemZ', 'ItemJ', ['Item6', 'Item5'], 'ItemP']]
Or, closer to your expected result (but still not exactly the same, as the order is scrambled up because of the intermediate step with the dictionary) using this instead:
def to_list(d):
return [[i] + [to_list(d[i])] if d[i] else i for i in d]
Output:
>>> print(to_list(dictionary)[0])
['ItemB', ['ItemZ', ['ItemJ', ['Item6', 'Item5']], 'ItemP']]