7 Pythonic Ways to Copy a Dictionary

5/5 - (12 votes)

Problem Formulation and Solution Overview

This article will show you how to copy a Dictionary in Python 7 different ways.

To make it more interesting, we have the following running scenario:

Mr. Smith, a High School Math Teacher, has developed an exciting way to grade multiple-choice exams. He has designed a Dictionary with the exam question number and answer as key:value pairs. How can Mr. Smith make a copy of this structure to modify for future exams?

exam_format = {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}

πŸ’¬ Question: How would we write code to create a copy of a Dictionary in Python?

We can accomplish this task using one of the following options:


Method 1: Use dict() and Dictionary Comprehension

This method uses the dict() function to create and return a new Dictionary object

Example 1:

q1_exam = dict(exam_format)

q1_exam[1] = 'C'
q1_exam[2] = 'D'
q1_exam[5] = 'A'
print(q1_exam)

The first line in the above code snippet uses the dict() function and passes it one (1) argument: exam_format (created earlier). These results save to q1_exam.

The following lines modify three (3) values for the q1_exam. The results are output to the terminal.

q1_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}

Example 2:

Alternatively, we could call the dict() function and pass it Dictionary Comprehension as an argument to the same.

q1_exam = dict((k,v) for k, v in exam_format.items())

q1_exam[1] = 'C'
q1_exam[2] = 'D'
q1_exam[5] = 'A'
print(q1_exam)  

The output is identical to that shown above.

Python dict() β€” A Simple Guide

Method 2: Use Dictionary Comprehension

This method uses Dictionary Comprehension to create and return a new Dictionary object.

q2_exam = {k:v for k,v in exam_format.items()}

q2_exam[2] = 'B'
q2_exam[3] = 'E'
q2_exam[5] = 'A'

print(q2_exam) 

The first line in the above code snippet uses Dictionary Comprehension to create a copy of the exam_format (created earlier). These results save to q2_exam.

The following lines modify three (3) values for the q2_exam. These results are then output to the terminal.

q2_exam:        {1: 'B', 2: 'B', 3: 'E', 4: 'D', 5: 'A'}
Python Dictionary Comprehension - A Powerful One-Liner Tutorial

Method 3: Use update()

This method uses the update() function to create and return a new Dictionary object.

q3_exam = {}
q3_exam.update(exam_format)
print(q3_exam)  

The first line in the above code snippet declares an empty Dictionary. These results save to q3_exam.

The following line calls q3_exam and appends the update() function to it. This function is passed one (1) argument: exam_format (created earlier). These results are then output to the terminal.

q3_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}
Python Dictionary update() Method

Method 4: Use unpacking()

This method uses the unpacking function to create and return a new Dictionary object.

q4_exam = {**exam_format}
print(q4_exam)  

The first line in the above code snippet creates a Dictionary and, using unpacking, passes all elements of exam_format. These results save to q4_exam. How Pythonic!

The results are output to the terminal.

q4_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}

✨A Finxter Favourite!


Method 5: Use copy()

This method uses the copy() function to create and return a new Dictionary object. This function is referred to as a shallow copy as it creates references to the original Dictionary.

import copy

exam_format2 = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term = exam_format2.copy()
print(mid_term)

mid_term[1].append(4)
print(exam_format2)
print(mid_term)

The first line in the above code snippet imports the copy library. This allows access to the copy() function.

The following line declares a new exam format for Mid Term exams. The results save to exam_format2. Next, a shallow copy of this Dictionary is made by appending the copy() function to exam_format2. These results save to mid_term and are then output to the terminal.

mid_term:        {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}

The following highlighted section adds a new element to mid_term then, exam_format2 and mid_term are then output to the terminal.

exam_format2:     {1: [1, 2, 3, 4], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term:         {1: [1, 2, 3, 4], 2: [1, 2, 3], 3: [1, 2, 3]}

Notice how both are updated. When coding, be careful with this option, as it may cause issues.


Method 6: deepcopy()

This method uses the deepcopy() function to create and return a new Dictionary object. This function is called a deep copy as it creates a new Dictionary object.

import copy

exam_format2 = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term = copy.deepcopy(exam_format2)
print(mid_term)

mid_term[1].append(4)
print(exam_format2)
print(mid_term)

The above code snippet is almost the same as in Method 5 (copy()). However, this code calls the deepcopy() function and passes it one (1) argument: exam_format2. The results save to mid_term and are then output to the terminal.

mid_term:        {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}

The following highlighted section adds a new element to mid_term then, exam_format2 and mid_term are then output to the terminal.

exam_format2:     {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term:         {1: [1, 2, 3, 4], 2: [1, 2, 3], 3: [1, 2, 3]}

Using deepcopy(), only mid_term was updated.


Bonus: Putting it Together

We decided that Method 4 was the best way to go, and we wrote the code below using this option.

The grade is automatically calculated when Mr. Smith retrieves his students’ results from his online multiple-choice exams. The only change would be the answers in exam_format for any future exams.

exam_format = {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}
q4_exam = {**exam_format}

students = {'Amy': {1: 'B', 2: 'E', 3: 'C', 4: 'B', 5: 'D'},
            'Ben': {1: 'C', 2: 'E', 3: 'A', 4: 'D', 5: 'D'},
            'Joe': {1: 'E', 2: 'C', 3: 'A', 4: 'B', 5: 'D'}}

for s_name, s_answers in students.items():
    correct = 0

    for s_num in s_answers:
        for exam_q in exam_format:
            if (s_num == exam_q) and (s_answers[s_num] == exam_format[exam_q]):
                correct += 1
    print(s_name, correct)


Summary

This article has provided seven (7) ways to copy a Dictionary to select the best fit for your coding requirements.

Good Luck & Happy Coding!