3

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?

ThePhi
  • 2,373
  • 3
  • 28
  • 38
  • 2
    I have never seen someone do ```dct[x] = dct = dct.get(x, dict()) ``` in fact I am surprised it doesn't raise an error! – Sabito stands with Ukraine May 25 '20 at 08:30
  • 1
    FWIW, the relevant part of the language documentation is [here](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements): "An assignment statement evaluates the expression list [...] and assigns the single resulting object to each of the target lists, from left to right." – Mark Dickinson May 25 '20 at 08:32

0 Answers0