繁体   English   中英

Python:默认字典初始化

[英]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。

问题出在代码片段的以下两行中 -

dd = defaultdict(lambda : "Key not    found")
dd = {'a':1,'b':2}

在第一行中,您正在创建一个defaultdict对象并且dd指向该对象 - dict_object

在第二行中,您正在创建一个字典,现在将其引用保存到dd - 在此处输入图片说明 因此,现在正如您在上图中所看到的, dd指向在第二行中创建的新字典。 由于dd所指的这个新字典没有名为“c”的键,因此您会收到“找不到键”错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM