考虑此代码
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: {}}
[帮助我了解为什么在第一种情况下,在每种情况下都出现'仅应...”列表,而不是第二种情况。字典是一成不变的,但我不明白为什么会得到不同的结果。
谢谢,
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
您要在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': []}}}