Ibrahim-a-Ibrahim
Ibrahim-a-Ibrahim

Reputation: 33

How to avoid overwriting the data from a list to a dictionary using for loop?

I have a nested dictionary as follows:

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}

I am using a for loop to fill up the values in the nested dictionary as follows:

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 is a list. Its values are changed once the step changed (It is defined based on function outside the loop).

Here, using the print function, it is clear that the values of AllpuVmVa at each step are different, but the values stored in (results['solution']['nw'][str(c)]['bus'][b]["vm"]['a']) and (results['solution']['nw'][str(c)]['bus'][b]["va"]['a']) are the same for all the steps, which is equal to the last step. It sounds that there is overwriting for the data.

Is there any idea to fix this issue?

Upvotes: 1

Views: 85

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195553

The problem is, that you assign the same dictionary stored in bus to every value in nw dict. To fix the issue, you can make new bus dictionary every iteration. For example:

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}

Upvotes: 2

Related Questions