Click for All Topics
.copy()
method doesn’t take any argument.
Syntax –
dictionary.clear()
Parameters –
Example 1 –
my_dict={'one':1,'two':2,'three':3,'four':4,'five':5}
print("Original dictionary:\n",my_dict)
copied_dictionary=my_dict.copy()
print("Copied dictionary:\n",copied_dictionary)
# Output -
# Original dictionary:
# {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
# Copied dictionary:
# {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
.copy()
method and store the copied dictionary in the copied_dictionary variable.Example 2- Let’s see if modifying the original dictionary affects the copied dictonary or not.
dct={'vowels':['a','e','i','o','u'],'hello':'world!'}
print("Original Dictionary:\n",dct)
dct_copy=dct.copy()
print("Copied dictionary:\n",dct_copy)
dct['hello']='Python'
print("Modify original dictionary:\n",dct)
print("Copied dictionary:\n",dct_copy)
# Output -
# Original Dictionary:
# {'vowels': ['a', 'e', 'i', 'o', 'u'], 'hello': 'world!'}
# Copied dictionary:
# {'vowels': ['a', 'e', 'i', 'o', 'u'], 'hello': 'world!'}
# Modify original dictionary:
# {'vowels': ['a', 'e', 'i', 'o', 'u'], 'hello': 'Python'}
# Copied dictionary:
# {'vowels': ['a', 'e', 'i', 'o', 'u'], 'hello': 'world!'}
Example 3- create a copy of a dictionary without using an in-built method e.g. .copy()
student = {
"name": "ABC",
"age": 20,
"major": "Computer Science",
"grades": [90, 85]
}
new_dict={}
for key, value in student.items():
new_dict[key] = value
print("Original dictionary:\n",student)
print("Copied dictionary:\n",new_dict)
# Output -
# Original dictionary:
# {'name': 'ABC', 'age': 20, 'major': 'Computer Science', 'grades': [90, 85]}
# Copied dictionary:
# {'name': 'ABC', 'age': 20, 'major': 'Computer Science', 'grades': [90, 85]}
Example –
my_dict={'A':10,'B':20,'C':30,'D':40,'E':50}
my_dict1=my_dict1
print("Original dictionary:\n",my_dict)
print("Copied dictionary:\n"my_dict1)
my_dict.update({'F':60})
print("\nModified original dictionary:\n",my_dict)
print("Copied dictionary:\n",my_dict1)
# Output -
# Original dictionary:
# {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
# Copied dictionary:
# {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
# Modified original dictionary:
# {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50, 'F': 60}
# Copied dictionary:
# {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50, 'F': 60}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India