Home > Net >  Keeping different dictionary versions in a list
Keeping different dictionary versions in a list

Time:04-27

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

[{'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.

CodePudding user response:

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)

CodePudding user response:

You need to initialize the send_this variable with a reference to your dictionaries:

fruits = {'a': 'apricot', 'b': 'bagel', 'c': 'carrot'}
template = {'a': 'apple', 'b': 'banana', 'c': 'coconut'}

send_this = [fruits, template]
print(send_this)

Output:

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