So I have a list of tuples of the form:
my_list=[('a','aa','aaa',0),('a','aa','aab',1),('a','ab','aba',2)]
And I need it to convert it to a nested dictionary:
out={'a':{'aa':{'aaa':0,'aab':1},'ab':{'aba':2}}}
The crucial piece of my setting is that I do not know in advance the length of the tuples in my_list (4 is just an example). Is there an easy way to generalize the cases I saw in other answers (e.g. Python list of tuples to nested dict or Convert a list of variable length Tuples into Dictionary) beyond the fixed 3-element tuples they use?
I made various attempts with recursive functions but I do not have anything close to a solution.
CodePudding user response:
Just loop over the first keys, setting aside the last pair of items which will be a key-value pair, and set dictionaries in-between (using setdefault
here, but you could do that part manually):
result = {}
for *keys, last_key, value in my_list:
current = result
for key in keys:
current = current.setdefault(key, {})
current[last_key] = value
Just to be explicit by what I mean by "manually" (I guess I should rather say "explicitly"):
result = {}
for *keys, last_key, value in my_list:
current = result
for key in keys:
if key not in current:
current[key] = {}
current = current[key]
current[last_key] = value