为什么嵌套字典填错了?

Why nested dictionary is filled wrongly?

我有一个这样设计的空嵌套字典:

{'PEAR': {'GREEN': [], 'YELLOW': [], 'RED': []}, 'APPLE': {'GREEN': [], 'YELLOW': [], 'RED': []}, 'COURGETTE': {'GREEN': [], 'YELLOW': [], 'RED': []}}

这是我的代码:

dictSub = {'RED' : [], 'GREEN' : [], 'YELLOW' : []}
arrMainCodes = ['APPLE', 'PEAR', 'COURGETTE']
dictAll = {}
numbers = {1 : [1, 2, 3], 2 : [4, 56, 7], 3 : [8, 2, 10]}

for item in arrMainCodes:
    dictAll[item] = dictSub
print(dictAll)
dictAll['PEAR']['RED'].append(478)
dictAll['PEAR']['RED'].append(47)
dictAll['PEAR']['RED'].append(8)
print(dictAll)
ITEM = [478, 7, 56]
for i in ITEM:
    if i not in dictAll['PEAR']['RED']:
        dictAll['PEAR']['RED'].append(i)
print(dictAll)

我试图以这样的方式填充它,即只填充键 'PEAR' 的子列表 'RED'。然而,我的结果是这样的:

{'PEAR': {'GREEN': [], 'YELLOW': [], 'RED': [478, 47, 8, 7, 56]}, 'APPLE': {'GREEN': [], 'YELLOW': [], 'RED': [478, 47, 8, 7, 56]}, 'COURGETTE': {'GREEN': [], 'YELLOW': [], 'RED': [478, 47, 8, 7, 56]}}

如你所见,'RED' 都已填充,而我只想填充红梨。

我做错了什么?如何解决?

它们都是对单个词典的引用。您的前四个语句是唯一实际创建新字典对象的语句;您的 for 循环只会创建其他名称,这些名称都指向同一个名称。

您可以通过替换此作业来解决该问题:

dictAll[item] = dictSub

有了这个:

dictAll[item] = dictSub.copy()

这将为您提供单独的词典,但每个词典仍将引用相同的列表。为确保所有内容都是全新副本,请改用 deepcopy()

dictAll[item] = dictSub.deepcopy()

问题是python。 Python 从不复制任何对象。因此,每当您分配一个字典或数组时,都会保留一个引用,并且每当您更改一个时,更改都会反映在所有引用中。 你可以做到这一点。

arrMainCodes = ['APPLE', 'PEAR', 'COURGETTE']
dictAll = {}
numbers = {1 : [1, 2, 3], 2 : [4, 56, 7], 3 : [8, 2, 10]}

for item in arrMainCodes:
    dictAll[item]={'RED' : [], 'GREEN' : [], 'YELLOW' : []}
print(dictAll)
dictAll['PEAR']['RED'].append(478)
dictAll['PEAR']['RED'].append(47)
dictAll['PEAR']['RED'].append(8)
print(dictAll)
ITEM = [478, 7, 56]
for i in ITEM:
    if i not in dictAll['PEAR']['RED']:
        dictAll['PEAR']['RED'].append(i)
print(dictAll)

每次都会用新列表创建单独的字典。