I'm trying to build a new key into my dictionary by taking another one from the same dictionary. And I would like to change some values in that new key.
Let's look at an example:
# Here is a dictionary
my_dict = {'one' : {'same': 'test_1'}}
# Create a new key based on a pre-existing one in our dictionary
my_dict['two'] = my_dict['one']
# Asign a new value to that new key:
my_dict['two']['same'] = 'test_2'
What I expected when print(my_dict)
:
{'one': {'same': 'test_1'}, 'two': {'same': 'test_2'}}
But here is what I got:
{'one': {'same': 'test_2'}, 'two': {'same': 'test_2'}}
My question is: why both one
and two
have changed? Why not just two
like I asked?
Also if we try:
# Creating a dictionary but this time, fully prepared
my_dict = {'one': {'same': 'test_1'}, 'two': {'same': 'test_1'}}
# Changing a value in key two:
my_dict['two']['same'] = 'test_2'
We get print(my_dict)
:
{'one': {'same': 'test_1'}, 'two': {'same': 'test_2'}}
Which this time, is the output I expected.
What's the difference between this two methods?
Edit Answer:
It was not working because at my_dict['two'] = my_dict['one']
it was assigning the same reference to both keys. So if one of them is changed, all the corresponding references will change too.
To avoid this as suggested in the answers: my_dict['two'] = my_dict['one'].copy()
will copy the key but without the reference.
More info in another post: https://stackoverflow.com/a/2465932/10972294
This post is a duplicated, but as suggested here: https://meta.stackoverflow.com/a/265737/10972294
This post still might help for those who are not aware of the copy & reference stuff in python dictionaries.