Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - COPY FROM DICTIONARY


How to copy one Dictionary to the other ?


There are two ways by which we can copy one Dictionary to the other.


  1. Using the method 'dict( )'

  2. Using the method 'copy( )'

Let us look at the first way using the 'dict( )' method.


Example :


x = {
    5 : "Is a Number", 
    "John": "Is a Name", 
    "Python": "Is a Language"
}
y = dict(x)
print("The Copied Dictionary is ",y)


Output :



  The Copied Dictionary is {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language'}

So , in the above code we have created a 'Dictionary' and initialised to the variable 'x' .


x = {
    5 : "Is a Number", 
    "John": "Is a Name", 
    "Python": "Is a Language"
}

Then we have used the 'dict( )' method that takes the Dictionary 'x' as parameter and creates a new Dictionary that would be the exact copy of 'x' .


Then assign it to 'y' .


y = dict(x)

And if we see the below output ,


The Copied Dictionary is {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language'}

The new variable 'y' is an exact copy of 'x' .


Now , let us look at the second way of copying a Dictionary using 'copy( )' method.


Example :


x = {
    5 : "Is a Number", 
    "John": "Is a Name", 
    "Python": "Is a Language"
}
y = x.copy()
print("The Copied Dictionary is ",y) 


Output :



  The Copied Dictionary is {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language'}

Similarly , in the above code we have created a 'Dictionary' and initialised to the variable 'x' .


x = {
    5 : "Is a Number", 
    "John": "Is a Name", 
    "Python": "Is a Language"
}

Then we have used the 'copy( )' method that Dictionary 'x' invokes and creates a new Dictionary that would be the exact copy of 'x' .


Then assign it to 'y' .


y = x.copy( )

And if we see the below output ,


The Copied Dictionary is {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language'}

The new variable 'y' is an exact copy of 'x' .


Note : Do not use the '=' operator to copy a Dictionary to the other(i.e. If there are two Dictionaries 'x' and 'y'. Do not use y = x). Because in that case any changes made to the Dictionary 'x' will be reflected in the copied Dictionary 'y'.