Computer >> Computer tutorials >  >> Programming >> Python

Python - Ways to Copy Dictionary


A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. They copy() method returns a shallow copy of the dictionary.

Example

#creating a dictionary
original = {1:'vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from the list Only new list becomes empty as #copy() does shallow copy.
new.clear()
print('new: ', new)
print('original: ', original)
# between = and copy()
original = {1:'Vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
original = {1:'one', 2:'two'}
# copying using =
new = original
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)

Output

('new: ', {})
('original: ', {1: 'vishesh', 2: 'python'})
('new: ', {})
('original: ', {1: 'Vishesh', 2: 'python'})
('new: ', {})
('original: ', {})