My question emerged when looking here to find how to create a trie in python. The following code was given in the top-voted answer:
>>> _end = '_end_'
>>>
>>> def make_trie(*words):
... root = dict()
... for word in words:
... current_dict = root
... for letter in word:
... current_dict = current_dict.setdefault(letter, {})
... current_dict[_end] = _end
... return root
...
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}},
'z': {'_end_': '_end_'}}}, 'f': {'o': {'o': {'_end_': '_end_'}}}}
I don't understand what purpose the line "current_dict = root" serves; seems like deleting that line and substituting all current_dict with root would do the same thing. (This same thought is expressed in this reply but with no answer.) I know this actually doesn't work as I tried it and an empty dictionary was returned.
I also tried putting print statements in the second for loop to see how current_dict and root were updated. I thought that since they were set to be equal, they referred to the same dictionary and would be updated simultaneously, but that wasn't the case.
Clearly, I have a fundamental misunderstanding of this interaction. Help?