0

I've got this code snippet, which converts a flat list to a dictionary: (for example, from:

`X = [['A', 'B', 'C'], ['A', 'B', 'D'],['W','X'],['W','Y','Z']]`

to

{'A': {'B': {'C': {}, 'D': {}}}, 'W': {'X': {}, 'Y': {'Z': {}}}}

the code:

d = {}

for path in X:
    current_level = d
    for part in path:
        if part not in current_level:
            current_level[part] = {}
        current_level = current_level[part]
        print('current_level = ', current_level)
        print('d = ', d)
print(d)

and here's the output:

current_level =  {}
d =  {'A': {}}
current_level =  {}
d =  {'A': {'B': {}}}
current_level =  {}
d =  {'A': {'B': {'C': {}}}}
current_level =  {'B': {'C': {}}}
d =  {'A': {'B': {'C': {}}}}
current_level =  {'C': {}}
d =  {'A': {'B': {'C': {}}}}
current_level =  {}
d =  {'A': {'B': {'C': {}, 'D': {}}}}
current_level =  {}
d =  {'A': {'B': {'C': {}, 'D': {}}}, 'W': {}}
current_level =  {}
d =  {'A': {'B': {'C': {}, 'D': {}}}, 'W': {'X': {}}}
current_level =  {'X': {}}
d =  {'A': {'B': {'C': {}, 'D': {}}}, 'W': {'X': {}}}
current_level =  {}
d =  {'A': {'B': {'C': {}, 'D': {}}}, 'W': {'X': {}, 'Y': {}}}
current_level =  {}
d =  {'A': {'B': {'C': {}, 'D': {}}}, 'W': {'X': {}, 'Y': {'Z': {}}}}

So with current_level = d, it seems we are passing a reference to the dictionary d. Indeed, this dictionary doesn't appear anymore in the code after that.

But when we do: current_level = current_level[part]: the current_level dict is given the value an empty dict {} whereas d doesn't change (see the output).

So I'm confused: is it a reference to the dict or a distinct copy?

ThePhi
  • 2,373
  • 3
  • 28
  • 38

1 Answers1

0

It is always by reference but not the same reference as you would have in C++.
current_level = d means that current_level is now pointing to d and not that it is a reference to d.

This means that when you do current_level = current_level[part], you do not update d with current_level[part] but update the value of the object pointed by current_level to be current_level[part]

Sylvaus
  • 844
  • 6
  • 13