使用for循环python更新嵌套字典

时间:2020-04-21 23:48:41

标签: python

我正在尝试在for循环中更新嵌套字典,但最终输出似乎覆盖了先前的键值。

a = {}
b = {}
f=0
for x in range(3):
    a['test1'] = 1+f
    a['test2'] = 2+f
    a['test3'] = 3+f
    f = f+1
    b[f] = a

print(b)

输出:

{1: {'test1': 3, 'test2': 4, 'test3': 5}, 2: {'test1': 3, 'test2': 4, 'test3': 5}, 3: {'test1': 3, 'test2': 4, 'test3': 5}}

预期输出:

{1: {'test1': 1, 'test2': 2, 'test3': 3}, 2: {'test1': 2, 'test2': 3, 'test3': 4}, 3: {'test1': 3, 'test2': 4, 'test3': 5}}

4 个答案:

答案 0 :(得分:1)

我认为这样做

a = {}
b = {}

for f in range(3):
    a['test1'] = 1+f
    a['test2'] = 2+f
    a['test3'] = 3+f
    b[f] = a

答案 1 :(得分:0)

字典是可变的,因此当将字典分配给另一个变量时,将仅分配一个指针,而不是原始字典的副本。如果更改原始词典,则将更改与该词典的指针关联的所有变量。为避免这种情况,您只需要b[f]=a.copy()而不是b[f]=a。这是针对单层词典的;如需更深入的了解,请使用copy.deepcopy

答案 2 :(得分:0)

执行b[f]=a时,将字典f的项b分配给字典a,因此,如果您更改字典a的值,则所有元素b中的,将指向此修改后的a。而是尝试创建一个新的词典并更新b的值:

b = {}
f=0
for x in range(3):
    a = {}
    a['test1'] = 1+f
    a['test2'] = 2+f
    a['test3'] = 3+f
    f = f+1
    b[f] = a

print(b)
{1: {'test1': 1, 'test2': 2, 'test3': 3}, 2: {'test1': 2, 'test2': 3, 'test3': 4}, 3: {'test1': 3, 'test2': 4, 'test3': 5}}

或者您可以尝试使用这种衬垫:

b = {f:{'test{}'.format(i):i+f for i in range(1,4)} for f in range(1,4)}
print(b)
{1: {'test1': 2, 'test2': 3, 'test3': 4}, 2: {'test1': 3, 'test2': 4, 'test3': 5}, 3: {'test1': 4, 'test2': 5, 'test3': 6}}

答案 3 :(得分:0)

这是一个可能的解决方案

b = {}
f=0
for x in range(3):
#add the part below

    a = {}

################

    a['test1'] = 1+f
    a['test2'] = 2+f
    a['test3'] = 3+f
    f = f+1
    b[f] = a



print(b)

在循环外包含“ a”是在每次迭代中更新其值,重置a的值使您可以相应地执行代码。