簡體   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