python

How to copy a dictionary in Python

In this tutorial, we are going to see how to copy a dictionary in Python. Dictionary in Python is an unordered collection of values, which maps one set of objects(keys) to another set of objects(values) unlike other data types that contain only one value as an element.

When we assign dictionaryA = dictionaryB these refers to the same dictionary. In this tutorial we will see different ways to copy a dictionary to another dictionary.
 

 

How to copy a dictionary using copy() method

The copy() method returns a shallow copy of the existing dictionary.

# Dictionary of languages
languages_dic = {
    "Python": 55,
    "Java" : 142,
    "PHP" : 32,
    "C" : 13,
} 

# copy the languages dictionary into copy_dic
copy_dic = languages_dic.copy() 

# Display the initial dictionary 
print("Initial dictionary = ", languages_dic) 

# Display the copy of the dictionary 
print("Copy of the dictionary = ", copy_dic)

Output:

Initial dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}
Copy of the dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}

 

 

How to copy a dictionary using the dict() constructor

dict() is a constructor that creates a dictionary in Python.

# Dictionary of languages
languages_dic = {
    "Python": 55,
    "Java" : 142,
    "PHP" : 32,
    "C" : 13,
} 

# copy the languages dictionary into copy_dic
copy_dic = dict(languages_dic) 

# Display the initial dictionary 
print("Initial dictionary = ", languages_dic) 

# Display the copy of the dictionary 
print("Copy of the dictionary = ", copy_dic)

Output:

Initial dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}
Copy of the dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}

 

How to copy a dictionary using dict.items() method

items() returns an iterable sequence of all key-value pairs in the dictionary.

# Dictionary of languages
languages_dic = {
    "Python": 55,
    "Java" : 142,
    "PHP" : 32,
    "C" : 13,
} 

# copy the languages dictionary into copy_dic
copy_dic = {key:value for key, value in languages_dic.items()} 

# Display the initial dictionary 
print("Initial dictionary = ", languages_dic) 

# Display the copy of the dictionary 
print("Copy of the dictionary = ", copy_dic)

Output:

Initial dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}
Copy of the dictionary = {'Java': 142, 'C': 13, 'Python': 55, 'PHP': 32}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *