如何避免使用for循环将列表中的数据覆盖到字典中?

时间:2020-10-04 13:10:08

标签: python dictionary

我有一个嵌套的字典,如下所示:

bus = dict()
pvsystem = dict()
    for j in range(500):
        bus[j] = {'vm': {'a': 1, 'b': 1, 'c': 1}, 'va': {'a': 1, 'b': 1, 'c': 1}}
    nw = dict()
    for step in range(24):
        c = step + 1
        nw[str(c)] = {'bus': bus}
    solution = {'nw': nw}
    results = {'solution': solution}

我正在使用for循环来填充嵌套字典中的值,如下所示:

for step in range(10):
    c = step + 1
    for b in range(20):
        AllpuVmVa = dss.Bus.puVmagAngle()
        results['solution']['nw'][str(c)]['bus'][b]["vm"]['a'] = AllpuVmVa[0]
        results['solution']['nw'][str(c)]['bus'][b]["va"]['a'] = AllpuVmVa[1]
    print("Step: ", c, " Voltages: ", AllpuVmVa)

AllpuVmVa是一个列表。更改步骤后,其值就会更改(它是根据循环外的函数定义的。)

在这里,使用print函数可以很明显地看出,每个步骤中AllpuVmVa的值是不同的,但是存储在(results['solution']['nw'][str(c)]['bus'][b]["vm"]['a'])和({{1} })对于所有步骤都相同,这与最后一步相同。听起来有数据被覆盖。

有解决此问题的主意吗?

1 个答案:

答案 0 :(得分:1)

问题是,您将bus中存储的相同字典分配给nw字典中的每个值。要解决此问题,您可以在每次迭代时制作新的bus字典。例如:

bus = dict()
pvsystem = dict()

def get_bus():
    return {j: {'vm': {'a': 1, 'b': 1, 'c': 1}, 'va': {'a': 1, 'b': 1, 'c': 1}} for j in range(500)}

nw = dict()
for step in range(24):
    c = step + 1
    nw[str(c)] = {'bus': get_bus()}     # <-- use get_bus() here

solution = {'nw': nw}
results = {'solution': solution}
相关问题