关于在Python中创建递归字典的问题

问题描述 投票:2回答:1

我在网上看到了这段代码:

class StreamChecker(object):
    def __init__(self, words):
        """
        :type words: List[str]
        """
        print(words)
        self.waitlist = []
        self.trie = dict()
        for word in words:
            temp_dict = self.trie
            for letter in word:
                temp_dict = temp_dict.setdefault(letter, dict())

            temp_dict['#'] = '#'

if __name__ == '__main__':
    a = StreamChecker(['abc', 'wef', 'ykj'])
    print(a.trie)

启动后,打印self.trie获得{'a': {'b': {'c': {'#': '#'}}}, 'w': {'e': {'f': {'#': '#'}}}, 'y': {'k': {'j': {'#': '#'}}}}

我对代码中的这一行'temp_dict = temp_dict.setdefault(letter, dict())'感到困惑。由于每次setdefault将返回一个空的字典{},为什么self.trie每次都会更改,因为setdefault仅用于一个空的字典?据我了解,self.trie将仅对每个word进行一次更改,并且self.trie应该类似于{'a': {}, 'w': {}, 'y': {}}

有人可以向我解释吗?谢谢

python dictionary
1个回答
3
投票
>>> help(dict.setdefault)
setdefault(self, key, default=None, /)
    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

一个空字典不一定与另一个空字典相同。发生的是该行

temp_dict = temp_dict.setdefault(letter, dict())

首先在当前temp_dict上添加一个新键(对应的值为空dict),然后返回对该新添加值的引用。当它在循环中运行时,它最终以递归方式将新字典添加到原始字典中(即self.trie)。

由于我们要修改的嵌套dict包含在self.trie中,因此我们看到的更改反映在self.trie中。


可能有助于分解此语句:

temp_dict = temp_dict.setdefault(letter, dict())

进入此:

if letter not in temp_dict:
    temp_dict[letter] = dict()  # create a new dict, and put it inside the current dict
temp_dict = temp_dict[letter]   # jump inside the new dict that we just created, 
                                # or the existing dict that was there if it already existed.
© www.soinside.com 2019 - 2024. All rights reserved.