Reputation: 2053
So here's the abstract code of what I'm trying to do in python.
list_ = []
dict_ = {}
for i in range(something):
get_values_into_dict(dict_)
list_.append(dict_)
dict_.clear()
print list_
Here when I clear the dict_, obviously the all the elements in the list_ are deleted as they're just address mapped to the variable dict_.
What, I want is to copy the instance of dict_ so that I can store it in the list_.
Can someone explain me a way to store the obtained dict in every loop into the list_? Thanks in advance.
Upvotes: 3
Views: 859
Reputation: 1121834
You are adding a reference to the dictionary to your list, then clear the dictionary itself. That removes the contents of the dictionary, so all references to that dictionary will show that it is now empty.
Compare that with creating two variables that point to the same dictionary:
>>> a = {'foo': 'bar'}
>>> b = a
>>> b
{'foo': 'bar'}
>>> a.clear()
>>> b
{}
Dictionaries are mutable; you change the object itself.
Create a new dictionary in the loop instead of clearing and reusing one:
list_ = []
for i in range(something):
dict_ = {}
get_values_into_dict(dict_)
list_.append(dict_)
print list_
or better still, have get_values_into_dict()
return a dictionary instead:
list_ = []
for i in range(something):
dict_ = return_values_as_dict()
list_.append(dict_)
print list_
Upvotes: 4