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

Keeping different dictionary versions in a list

I’m trying to create a list of dictionaries in Python.

send_this = []

fruits = {'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}
template = {'a': 'apple', 'b': 'banana', 'c': 'coconut'}
for i in fruits.keys():
    send_this.append(template[i] = fruits[i])

This updates template and adds it to send_this but every iteration updates all the values stored in send_this instead of just adding a unique one.

I want the final result to be different dicts inside the list i.e

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

[{'a': 'apple', 'b': 'banana', 'c': 'coconut'}, {'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}]

but what I’m getting is something like this

[{'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}, {'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}]

I’m trying not to create the dictionary on the fly for each iteration since the vast majority of the dictionary doesn’t need to change for the whole loop.

>Solution :

The "problem" is that you keep adding the template dict to the list, so it’s the same object in each position of the list, so your list is holding three references to the same object.

You need to create a new dict one way or another for each loop iteration. Here’s a simple way which will work as long as your dict doesn’t itself include containers (in which case you’d need a deep copy):

send_this = []

fruits = {'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}
template = {'a': 'apple', 'b': 'banana', 'c': 'coconut'}
for i in fruits.keys():
    d = template.copy()
    d[i] = fruits[i]
    send_this.append(d)

print(send_this)
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