简体   繁体   中英

Updating Variables Pointing to the Same Dictionary in Python

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?

You have to reset current_dict = root for each single word, because current_dict = current_dict.setdefault(letter, {}) sets current_dict to a new empty dictionary or existing sub-dictionary of root if the key is already in the dict.

dict.setdefault(k, d) is a bit tricky because it does two things at the same time. It works just like dict.get and returns the value of the key k if it exists, otherwise the default value d . And if the key doesn't exist it also inserts it with d as the value.

So, as you see, current_dict is not always the root dict, but also refers to the sub-dicts when you're iterating over the letters in the word, and you have to reset it to root to start again at the top level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM