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

Python 如何避免使用for循环将列表中的数据覆盖到字典中?,python,dictionary,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}

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

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 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)
我使用for循环填充嵌套字典中的值,如下所示:

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 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']
)和(
results['solution']['nw'][str(c)]['bus'][b]['va]['a']
)中存储的值对于所有步骤都是相同的,这等于最后一步。听起来数据被覆盖了


有没有办法解决这个问题?

问题是,您将存储在
bus
中的同一个字典分配给
nw
dict中的每个值。要解决这个问题,您可以在每次迭代中创建新的
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}
bus=dict()
pvsystem=dict()
def get_总线():
为范围(500)内的j返回{j:{'vm':{'a':1,'b':1,'c':1},'va':{'a':1,'b':1,'c':1}}
nw=dict()
对于步进范围(24):
c=步骤+1
nw[str(c)]={'bus':get_bus()}#