我正在嘗試將字典的值更新為另一個串列提供的值,但更新也發生在所有先前的值上。
這是我的代碼片段:
dict = {'name' : 'shubham', 'age': 23}
listDict = [dict]*5
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
輸出來了:
[{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23}]
它應該來了:
[{'name': 'sh', 'age': 23},
{'name': 'shu', 'age': 23},
{'name': 'shub', 'age': 23},
{'name': 'shubh', 'age': 23},
{'name': 'shubha', 'age': 23}]
uj5u.com熱心網友回復:
當您執行該[dict]*5操作時,您之后會得到一個串列,其中包含 5 個對記憶體中同一字典物件的參考,因此當您編輯一個時,您實際上是在編輯所有這些物件。有關這一點的更多解釋,請查看 python 中 Mutable 和 Immutable 物件之間的區別(這是因為字典是可變的)。
要完成您想要的,您需要顯式地制作初始字典的副本。
listDict = [dict.copy() for i in range(5)]
這應該會產生您期望的結果。(還有一個友好的提示:你應該避免命名你的第一本字典dict:這會影響dict()功能并且讓人難以閱讀!)
uj5u.com熱心網友回復:
如果您創建這樣的字典串列:[dict]*5字典將相互鏈接。
所以我建議你用這種方式做乘法:
dict = {'name' : 'shubham', 'age': 23}
listDict = [ dict.copy() for i in range(5) ]
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
希望我有所幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441357.html
上一篇:有條件的字典的笛卡爾積
下一篇:大寫字母移位
