Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading