首页 > 解决方案 > d.get(key) 与 d[key] 的 Python defaultdict 有什么区别?

问题描述

我正在使用python defaultdict,我注意到了这一点:

from collections import defautdict

class TrieNode(object):
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.is_word = False

temp = TrieNode()

如果我做:

temp = temp.children['A'] 

temp将是一个新TrieNode实例

但如果我这样做:

   temp = temp.children.get('B')

temp可以是无。

为什么d.get(key)vsd[key]在 defaultdict 中表现不同?

标签: pythondictionarydefaultdict

解决方案


推荐阅读