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