How to increase each single element by one in a list of dictionaries?

list1 = [{'agent': 0, 'loc': (1, 2), 'timestep': 1}, {'agent': 1, 'loc': (1, 3), 'timestep': 2}]

I have list of dictionaries like this and I want to append 10 items identical to the last element of the original list and increase the value of each timestep by one to end up with the newly appended elements to have timesteps which increase in ascending order by one. I tried iterating through like below but it ended up increasing all of the timestamp values to some large number.

for i in range(10):
        list1.append(constraints[-1])
        list1[-1]['timestep'] +=1

Any help is appreciated
Thank you

>Solution :

The elements you’re appending all point to the same location in memory (i.e. are shallow copies, causing the undesired behavior). You can avoid this by using a list comprehension:

[{'agent': 0, 'loc': (1, 2), 'timestep': i} for i in range(1, 11)]

This outputs:

[
 {'agent': 0, 'loc': (1, 2), 'timestep': 1},
 {'agent': 0, 'loc': (1, 2), 'timestep': 2},
 ...
 {'agent': 0, 'loc': (1, 2), 'timestep': 9},
 {'agent': 0, 'loc': (1, 2), 'timestep': 10}
]

Leave a Reply