[英]Python : Default Dictionary Initialization
我创建了一个默认字典如下:
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"
谁能解释一下为什么第一个代码片段会抛出错误,而第二个代码片段按预期运行良好..
您已经用dd = {'a':1,'b':2}
覆盖了dd = defaultdict(lambda : "Key not found")
,因此defaultdict()
已成为dict()
。
请考虑删除第一个片段中的第 3 行。 这已经覆盖了类型为 defaultdict 的 dd。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.