Few prenotes
- Dict keys are immutable whereas values are mutable.
- When you use
=
, the new variable just references the old list
The value at key c
is a list. It is pointed to by the key at that place. On copying to a variable, the reference is passed. This can be confirmed by using id
.
>>> id(ddic['c'])
140726603094424
>>> id(n2)
140726603094424
As you see both the variables are pointing to the same element in memory. Hence any changes you make in one are reflected to the original one also.
To have a shallow copy of the list you can use [:]
as mentioned by Blckknght
>>> n2 = ddic['c'][:]
In python3, you can use (as mentioned by Padraic)
>>> n2 = ddic['c'].copy()
Using copy
module, you can prevent this from happening as in
>>> import copy
>>> n2 = copy.copy(ddic['c'])
>>> id(ddic['c'])
140726603094424
>>> id(n2)
140726603177640
Reference
Also note that as mentioned by Kasra in the comments, dicts don't have as separate space for them as they are data structures. You can find refernce in this document