簡體   English   中英

字典列表上的 For 循環更新所有以前的值

[英]For Loop on List of Dictionaries updating all previous values

我正在嘗試將字典的值更新為另一個列表提供的值,但更新也發生在所有以前的值上。

這是我的代碼片段:

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)

Output 來了:

[{'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}]

當你執行[dict]*5操作時,你之后得到的是 memory 中對同一個字典 object 的 5 個引用的列表,因此當你編輯一個時,你實際上是在編輯所有這些。 有關此的更多解釋,請查看 python 中可變對象和不可變對象之間的區別(這是因為字典是可變的)。

為了完成你想要的,你需要明確地制作初始字典的副本。

listDict = [dict.copy() for i in range(5)]

這應該會產生您期望的結果。 (也是一個友好的提示:你應該避免命名你的第一個字典dict :它掩蓋了dict() function 並且閱讀起來很混亂!)

如果你像這樣創建一個字典列表: [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)

希望我有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM