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

Viewed 42
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

3 Answers

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}
]

You can increment the timestep by using the .get() data structure and iterating through your list of dictionaries. .get() also allows you to name a default value if the value in the dictionary is none.

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

for dictionary in list1:
    dictionary['timestep'] = dictionary.get('timestep') + 1

print(list1)

Documentation for .get() can be found here: https://pythonexamples.org/python-dictionary-get/

I hope this helps!

Try to add .copy():

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

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

print(list1)

Prints:

[
    {"agent": 0, "loc": (1, 2), "timestep": 1},
    {"agent": 1, "loc": (1, 3), "timestep": 2},
    {"agent": 1, "loc": (1, 3), "timestep": 3},
    {"agent": 1, "loc": (1, 3), "timestep": 4},
    {"agent": 1, "loc": (1, 3), "timestep": 5},
    {"agent": 1, "loc": (1, 3), "timestep": 6},
    {"agent": 1, "loc": (1, 3), "timestep": 7},
    {"agent": 1, "loc": (1, 3), "timestep": 8},
    {"agent": 1, "loc": (1, 3), "timestep": 9},
    {"agent": 1, "loc": (1, 3), "timestep": 10},
    {"agent": 1, "loc": (1, 3), "timestep": 11},
    {"agent": 1, "loc": (1, 3), "timestep": 12},
]
Related