首页 > 解决方案 > Python:默认字典初始化

问题描述

我创建了一个默认字典,如下所示:

from collections import defaultdict
dd = defaultdict(lambda : "Key not    found")
dd = {'a':1,'b':2}
print(dd) 
print(dd['a']) # Prints 1
print(dd['c'])  # Throws KeyError

但是,下面的代码片段有效:

from collections import defaultdict
(lambda : "Key not    found")
dd['a']=1
dd['b']=2
print(dd) 
print(dd['a']) # Prints 1
print(dd['c'])  # Prints "Key not found"

谁能解释一下为什么第一个代码片段会引发错误,而第二个代码片段可以按预期运行..

标签: pythondictionarydefaultdict

解决方案


你已经覆盖dd = defaultdict(lambda : "Key not found")了,dd = {'a':1,'b':2}所以它defaultdict()变成了dict().


推荐阅读