The =
operator creates a new variable or data structure, but it basically points to the same object as before. So using the =
operator won't work.
You can use the list.copy()
method which returns a shallow copy of the list in the dictionary. Modifying this list will not modify the original dictionary.
mydict = {'a': ['apple', 'avocado'],
'b': ['banana', 'berry'],
'c': ['carrot', 'cucumber']}
fruits = mydict['a'].copy()
fruits.pop(0)
print(fruits) # returns ['avocado']
print(mydict) # returns {'a': ['apple', 'avocado'] ...}
Alternatively, use the Python copy module's copy()
or deepcopy()
method which will both work.
import copy
mydict = {'a': ['apple', 'avocado'],
'b': ['banana', 'berry'],
'c': ['carrot', 'cucumber']}
fruits = copy.copy(mydict['a']) # or copy.deepcopy(mydict['a'])
fruits.pop(0)
print(fruits) # returns ['avocado']
print(mydict) # returns {'a': ['apple', 'avocado'] ...}
The distinction between shallow (the copy()
method) and deep copying (the deepcopy()
method) is important but does not really apply in this case, because you are not copying a nested data structure (your dictionary) but only a list within that dictionary.
For example, shallow copying the dict and modifying the nested list also modifies the original:
import copy
mydict = {'a': ['apple', 'avocado'],
'b': ['banana', 'berry'],
'c': ['carrot', 'cucumber']}
fruits = copy.copy(mydict)
fruits['a'].append('apricot') # also changes mydict
print(fruits) # returns {'a': ['apple', 'avocado', 'apricot'] ...}
print(mydict) # also returns {'a': ['apple', 'avocado', 'apricot'] ...}
While deep copying does not:
import copy
mydict = {'a': ['apple', 'avocado'],
'b': ['banana', 'berry'],
'c': ['carrot', 'cucumber']}
fruits = copy.deepcopy(mydict)
fruits['a'].append('apricot') # also changes mydict
print(fruits) # returns {'a': ['apple', 'avocado', 'apricot'] ...}
print(mydict) # returns {'a': ['apple', 'avocado'] ...}
From the Python 3 docs on the copy module:
The difference between shallow and deep copying is only relevant for compound objects
(objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible)
inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies
into it of the objects found in the original.