Home > Software design >  How to increase each single element by one in a list of dictionaries?
How to increase each single element by one in a list of dictionaries?

Time:06-23

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

CodePudding user response:

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

CodePudding user response:

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!

  • Related