In this tutorial, we’ll learn how to use Python dictionary copy method using proper code examples with detailed explanation.
What is Python Dictionary Copy Method?
It is used to return a copy of Python dictionary having all the items. For instance, if we’ve a dictionary having two items, let’s say name and age then the copied dictionary will also have these items in it.
Syntax of Copy Method
dictName.copy()
- This method does not take any arguments.
- A copy of the original Python dictionary is returned using this copy() method. No updates to the original dictionary.
Example 1: Use Copy() Method on a Dictionary
simpleDictionary= {'name':'Yameen','age':24,'passion':'Football'} copiedDictionary= simpleDictionary.copy() print(copiedDictionary)
Output
{'name': 'Yameen', 'age': 24, 'passion': 'Football'} // copied dictionary
We’ve assigned the return value(copied dictionary) of copy method to a new dictionary.
Example 1: Copy() Method Returns Copied Dictionary
simpleDictionary={'name':'Yameen','age':24,'passion':'Football'} print(simpleDictionary.copy()) // returns a copy of the dictionary print(simpleDictionary)
Output
{'name': 'Yameen', 'age': 24, 'passion': 'Football'} //copied dictionary {'name': 'Yameen', 'age': 24, 'passion': 'Football'} // original dictionary
Example 3: Using = Operator to Copy Dictionary
Difference between Python dictionary copy() method and this = operator is that if you copy the dictionary using = operator and in future, if you pass a clear method to the copied dictionary, then the original dictionary will also be cleared. See below code:
originalDictionary={'name':'Yameen','age':24}
copiedDictionary=originalDictionary
print(copiedDictionary) // {'name': 'Yameen', 'age': 24}
copiedDictionary.clear()
print(copiedDictionary) // {}
print(originalDictionary) // {}
Output
{'name': 'Yameen', 'age': 24} // copied dictionary {} // copied dictionary {} // original dictionary
If you use the copy() method then clearing the copied dictionary won’t clear or make any changes to the original dictionary. See below example:
copiedDictionary=originalDictionary.copy() // use this in above code
Output
{'name': 'Yameen', 'age': 24} // copied dictionary {} // copied dictionary {'name': 'Yameen', 'age': 24} // original dictionary
Use copy method instead of directly passing/assigning the dictionary.
Conclusion
To conclude, we now have an in-depth knowledge of how to use Python dictionary copy method. I’d be very glad to have your feedback on this post. Thank you for reading it.
You may like to read:
How To Use Python Dictionary Clear Method – Easy Python Code Example
How To Properly Define And Use Python Dictionary – Easy Python Code Example