首页 > 解决方案 > 关于python中递归dict创建的问题

问题描述

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

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每次只会更改一次wordself.trie应该像{'a': {}, 'w': {}, 'y': {}}

谁可以给我解释一下这个?谢谢

标签: pythondictionary

解决方案


>>> 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(对应的值是一个空字典),然后返回对该新添加值的引用。当它在循环中运行时,它最终会递归地将新字典添加到原始字典(即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.

推荐阅读