The same deepcopy()
method could be utilized when you want to copy dictionaries or custom class objects.
The code on the right presents the code that safely copies the dictionary.
Run the code to get the following output:
Memory chunks: 30996264 44045800
Same memory chunk? False
Let's modify the movies list
a_dict movies: ['Goldfinger (1964)', 'You Only Live Twice', 'Diamonds Are Forever (1971)']
b_dict movies: ['Goldfinger (1964)', 'You Only Live Twice']
output
Code
import copya_dict = {
'first name': 'James',
'last name': 'Bond',
'movies': ['Goldfinger (1964)', 'You Only Live Twice']
}
b_dict = copy.deepcopy(a_dict)
print('Memory chunks:', id(a_dict), id(b_dict))
print('Same memory chunk?', a_dict is b_dict)
print("Let's modify the movies list")
a_dict['movies'].append('Diamonds Are Forever (1971)')
print('a_dict movies:', a_dict['movies'])
print('b_dict movies:', b_dict['movies'])
{{ dockerServerErrorMsg }}
×
{{ errorMsg }}
×
{{ successMsg }}
×