'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
[{'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 1:[1]
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)
Doing this with deepcopy you would:
import copy
template = {'a': 'apple', 'b': 'banana', 'c': 'coconut'}
d = copy.deepcopy(template)
d[i] = fruits[i]
Solution 2:[2]
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'}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremiah Payne |
| Solution 2 | Cardstdani |
