2

I'm just trying to change the value from a nested dictionary.

The first dictionary is empty and the second one is populated. When I'm trying to change the value of one of the item in the nested dictionary, also the value with the same key of the others items has been changed.

name = dict()
work = {"hour" : 4, "age":21}

name['bob'] = work
name['harry'] = work

name['bob']['hour'] = 7

Now I obtain this if i print the new name dictionary:

{'bob': {'hour': 7, 'age': 21}, 'harry': {'hour': 7, 'age': 21}}

I'd like to have this situation:

{'bob': {'hour': 7, 'age': 21}, 'harry': {'hour': 4, 'age': 21}}

Why does it change the hour from the dictionary of harry?

2
  • 2
    Use name['bob'] = work.copy() and name['harry'] = work.copy().It will pass the reference not the value. Commented May 5, 2020 at 14:56
  • 2
    They are both references to the same value. You're going to want to copy it. Commented May 5, 2020 at 14:58

2 Answers 2

1

This is because both names refer to the same element, i.e. references to the same value. You should copy the dict instead of simple assignment like the following:

name = dict()
work = {"hour" : 4, "age":21}

name['bob'] = work.copy()
name['harry'] = work.copy()

name['bob']['hour'] = 7
Sign up to request clarification or add additional context in comments.

1 Comment

you don't need to import copy for shallow copy
1

The problem is that you assign the same object that you defined before.

Try to use dict copy:

name = dict()
work = {"hour" : 4, "age":21}

name['bob'] = work.copy()
name['harry'] = work.copy()

name['bob']['hour'] = 7

If work was nested dictionary, you would have to use deepcopy (copy creates shallow copy which doesn't copy nested structures):

from copy import deepcopy
name['bob'] = deepcopy(work)
name['harry'] = deepcopy(work)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.