I've found a code to convert a flat dictionary into a nested dictionary:
def insert(dct, lst):
for x in lst[:-2]:
dct[x] = dct = dct.get(x, dict())
dct.update({lst[-2]: lst[-1]})
def convert_nested(dct):
# empty dict to store the result
result = dict()
# create an iterator of lists
# representing nested or hierarchial flow
lsts = ([*k.split("_"), v] for k, v in dct.items())
# insert each list into the result
for lst in lsts:
insert(result, lst)
return result
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# priniting initial dictionary
print ("initial_dictionary", str(ini_dict))
#--> initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for': 7}
# printing final dictionary
print ("final_dictionary", str(convert_nested(ini_dict)))
#--> final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks': {'for': 7}}}
I'm trying to understand each step it takes (that's not the point of my question here).
In particular, the inner function insert(dct, lst)
.
To debug this I've converted this to:
def insert(dct, lst):
for x in lst[:-2]:
dct = dct.get(x, dict())
dct[x] = dct
dct.update({lst[-2]: lst[-1]})
But to my surprise, the result is completely different (the endresult dictionary is empty).
I've thought a = b = c
would be the same as b = c
, a = b
?