Reputation: 900
In python 3.5.1
og_dict = {'name':'user1', 'salary':'1k'}
og_dict_list =[]
for i in range(2,5):
og_dict['salary'] = str(i)+'k'
og_dict_list.append(og_dict)
for og_dict_obj in og_dict_list:
print(og_dict_obj)
Above code produces following output :
{'name': 'user1', 'salary': '4k'}
{'name': 'user1', 'salary': '4k'}
{'name': 'user1', 'salary': '4k'}
But I am expecting below output :
{'name': 'user1', 'salary': '2k'}
{'name': 'user1', 'salary': '3k'}
{'name': 'user1', 'salary': '4k'}
Apparantely python modifies the existing dictionary only and does not create a new one. What can I do to solve this issue?
Is there exist a way to create a new dictionary object from existing one? Is there any other collection which is more suitable for this?
Upvotes: 3
Views: 16183
Reputation: 298
og_dict_list =[]
for i in range(2,5):
og_dict = {'name':'user1', 'salary':str(i) +'k'}
og_dict_list.append(og_dict)
for og_dict_obj in og_dict_list:
print(og_dict_obj)`enter code here
There is always a better way to do this. You can also use the update() method in Python to add new items to dictionaries.
Upvotes: 0
Reputation: 101919
As has been pointed out, it doesn't matter what you do, when in the loop you have:
for ob_dict_obj in ob_dict_list:
print(ob_dict) # wrong!
it always print the value for ob_dict
and doesn't matter what values you put in ob_dict_list
.
This said the problem is that you are modifying the only dictionary. You want to create a new one for each iteration:
og_dict = {'name':'user1', 'salary':'1k'}
og_dict_list =[]
for i in range(2,5):
new = og_dict.copy()
new['salary'] = str(i)+'k'
og_dict_list.append(new)
for og_dict_obj in og_dict_list:
print(og_dict_obj)
There is a number of ways to copy a dictionary, like just doing dict(of_dict)
instead of calling .copy()
. However, AFAIK, there is no single method that allows you to copy & update a dictionary at the same time.
However there isn't much point in having the og_dict
outside the loop at this point:
og_dict_list =[]
for i in range(2,5):
og_dict = {'name':'user1', 'salary':str(i) +'k'}
og_dict_list.append(og_dict)
for og_dict_obj in og_dict_list:
print(og_dict_obj)
To answer your broader question: the kind of behaviour you are looking for is typical of functional languages which have persistent data structures. However in imperative languages having an operation that copies & updates would be a simple way to shoot yourself on the foot by creating tons of unwanted copies.
All built-in cointainers act the same as dict
: update methods simply modify the current object and you have to explicitly copy the object to avoid the side effects.
Upvotes: 8