copy()

The syntax of the copy() method is as follows:

dict.copy() 

See the following example:

>>> Avengers ={'iron-man':"Tony", "CA":"Steve","BW":"Natasha"}
>>> Avengers
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>> Avengers2 = Avengers.copy()
>>> Avengers2
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>>

You can see that Avengers2 is an exact copy of Avengers. Do not confuse copy() with the assignment operator. Let's see the following example:

>>> A1 = {'iron-man':"Tony", "CA":"Steve","BW":"Natasha"}
>>> A2= A1
>>>
>>> A2
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>>
>>> CW= A1.copy()
>>> CW
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>>

Variable A1 and A2 hold the same dictionary, but the CW variable hold different dictionary. You can check the memory address of A1, A2, and CW:

>>> id(A1)
46395728
>>> id(A2)
46395728
>>> id(CW)
46136896
>>>

We can do one more thing. Let's add one more member to the A1 dictionary:

>>> A1
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>> A1["hulk"]= "Bruce-Banner"
>>> A1
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk': 'Bruce-Banner'}
>>> A2
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk': 'Bruce-Banner'}
>>> CW
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
>>>

We have changed the A1 dictionary and the changes would also be reflected by A2 since both hold the same memory address, whereas CW holds a different dictionary. Consider that you have a dictionary and you want to access a key, which does not exist in the dictionary. The interpreter shows KeyError as follows:

>>> A1 = {'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk': 'Bruce-Banner'}
>>> A1["panther"]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
A1["panther"]
KeyError: 'panther'
>>>

In the preceding code, you can clearly see the error. If this happens in running code, your code will not get fully executed. In order to deal with this situation, we will use the get() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.135.249