为什么我的字典在可变和不可变之间交替?

问题描述 投票:0回答:2

考虑此代码

from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)
print('Round 2, without SLOT')
test_dict = {}
new = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['this should only be in 3'] = []
pprint(test_dict)

具有此输出

> python -i .\test2.py
{0: {'slot': {'this should only be in 3': []}},
 1: {'slot': {'this should only be in 3': []}},
 2: {'slot': {'this should only be in 3': []}},
 3: {'slot': {'this should only be in 3': []}},
 4: {'slot': {'this should only be in 3': []}}}
Round 2, without SLOT
{0: {}, 1: {}, 2: {}, 3: {'this should only be in 3': []}, 4: {}}

[帮助我了解为什么在第一种情况下,在每种情况下都出现'仅应...”列表,而不是第二种情况。字典是一成不变的,但我不明白为什么会得到不同的结果。

谢谢,

python python-3.x immutability mutable
2个回答
0
投票

update方法不会为new['slot']中的每个条目复制test_dict的副本。

之后

test_dict = {}
new = {}
new['slot'] = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []

test_dict[k]['slot']是每个dict对相同k = 0, 1, ..., 4的引用。您可以通过id确认:

>>> for k in range(5): id(test_dict[k]['slot'])
...
4422633104
4422633104
4422633104
4422633104
4422633104
>>> id(new['slot'])
4422633104

0
投票

您要在dict的每个键中存储与new['slot']中存储的test_dict相同的实例:

from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    print(id(test_dict[k]['slot']))
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)

输出

4469588048
4469588048
4469588048
4469588048
4469588048
{0: {'slot': {'this should only be in 3': []}},
 1: {'slot': {'this should only be in 3': []}},
 2: {'slot': {'this should only be in 3': []}},
 3: {'slot': {'this should only be in 3': []}},
 4: {'slot': {'this should only be in 3': []}}}
© www.soinside.com 2019 - 2024. All rights reserved.