python中递归dict的创建问题

python中递归dict的创建问题,python,dictionary,Python,Dictionary,我在网上看到了这段代码: class StreamChecker(object): def __init__(self, words): """ :type words: List[str] """ print(words) self.waitlist = [] self.trie = dict() for word in words: temp_dic

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

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)
初始化后,print self.trie获取{'a':{'b':{'c':{},'w':{'e':{'f':{},'y':{'k':{'j':{}

我对代码中的这一行“temp_dict=temp_dict.setdefaultletter,dict”感到困惑。由于每次setdefault都会返回一个空dict{},既然setdefault只在一个空dict上使用,为什么每次都会更改self.trie?据我所知,self.trie对于每个单词只更改一次,self.trie应该像{'a':{},'w':{},'y':{}

有人能给我解释一下吗?谢谢

>>> 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.
一个空的dict不一定和另一个空的dict是同一个对象

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.

谢谢你的回复。我已经阅读了关于setdefault的文档,它只说如果该键不在dict中,则返回默认值,并且没有指定它是引用。我试着检查一下temp_dict的类型,它只显示dictionary。那么,有没有办法判断一个dict是否是对另一个dict的引用呢?这会发生在列表或元组等其他数据结构上吗?非常感谢@文斌旭一切都是参考。每种类型的每个变量都是对存储在某处的某些数据的引用。我们通常在谈论参考文献时省去中间环节,只参考参考文献所指向的数据,以简化我们的讨论。这里要理解的是,你可以有两个相同的dict,它们不是同一个对象,就像你在现实生活中可以有两个相同的对象坐在一起一样——它们不是同一个对象,只是它们的行为方式相同。列表或dict可以包含任何内容。在dict的情况下,键和值都是对数据的引用——数据可以是您想要的任何数据。列表或dict有可能包含自己,尽管您可能不应该这样做。或者它可以包含一个不同的列表/目录,这就是这里发生的事情。反过来,它可以包含其他东西,等等。