簡體   English   中英

如果要更改值,則使用for循環創建嵌套python詞典時為什么不起作用?

[英]Why does a nested python dictionary not work if it is created with a for-loop when you want to change a value?

如果我有一個通過編寫所有鍵和值創建的嵌套Python字典,則可以通過以下方法在內部字典中更改一個值: mainDict[outerKey][innerKey] = NewValue 但是,如果我使用for循環創建完全相同的字典,則當我嘗試更改內部值時,所有內部字典都會更改。 這是為什么?

我已經測試過獲取每個部分的值和值類型,對於顯式編寫的嵌套字典和使用for循環編寫的嵌套字典而言,它們似乎都完全相同。

帶有嵌套字典的Example1顯式編寫:

outerDict = {'outerA': {'innerA': 0, 'innerB': 0}, 'outerB': {'innerA': 0, 'innerB': 0}}

outer = 'outerB'
inner = 'innerB'
outerDict['outerB']['innerB'] = 'New Value'

print(outerDict)

結果:{'outerA':{'innerA':0,'innerB':0},'outerB':{'innerA':0,'innerB':'新值'}}

Example2使用for循環編寫的嵌套字典:

def dictCreate(outerKeys, innerKeys):
    innerDict = dict()
    for innerKey in innerKeys:
        innerDict[innerKey] = 0

    outerDict = dict()
    for outerKey in outerKeys:
        outerDict[outerKey] = innerDict
    return outerDict

outerKeys = ['outerA', 'outerB']
innerKeys = ['innerA', 'innerB']
outerDict = dictCreate(outerKeys, innerKeys)
outer = 'outerB'
inner = 'innerB'
outerDict['outerB']['innerB'] = 'New Value'

print(outerDict)

結果:{'outerA':{'innerA':0,'innerB':'新值'},'outerB':{'innerA':0,'innerB':'新值'}}

注意,在顯式編寫的嵌套字典的示例中,唯一更改的值是外部字典“ outerB” /內部字典“ innerB”中的值。

但是在使用for循環創建的示例中,內部字典的值在兩個外部字典中均更改了“ innerB”。 怎么會這樣? 還是我是唯一獲得這些結果的人?

因為它們是同一詞典,所以引用了2個不同的地方。

您的for循環:

 for outerKey in outerKeys:
     outerDict[outerKey] = innerDict

給每個外部詞典一個對相同 innerDict的引用-這就是為什么在所有outerDict值中看到innderDict任何更改的outerDict

這是完全可以預期的(在“ Python照設計的方式工作”的意義上)。

您正在使用相同的對象,即外部的每個循環都使用相同的引用。 因此,當您更改一個時,您將全部更改。

def dictCreate(outerKeys, innerKeys):
    innerDict = dict()
    for innerKey in innerKeys:
        innerDict[innerKey] = 0

    outerDict = dict()
    for outerKey in outerKeys:
        outerDict[outerKey] = innerDict # Here you are using the same list every iteration
    return outerDict

要解決此問題,您必須在每個循環中構造一個新列表:

def dictCreate(outerKeys, innerKeys):
    outerDict = dict()
    for outerKey in outerKeys:
        innerDict = dict()
        for innerKey in innerKeys:
            innerDict[innerKey] = 0
        outerDict[outerKey] = innerDict # Here you are now using a new list every iteration
    return outerDict

您可以使用dict理解使它變得更好

outerDict =  { outerKey : {innerKey : 0 for innerKey in innerKeys} for outerKey in outerKeys}

就像@Scott Hunter所說的那樣,您使用2個來自2個不同地方的引用。

您應該知道python如何處理可變對象和不可變對象

暫無
暫無

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

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