Copying Dictionaries in Python: Creating Duplicate Dictionaries

thumb_up 1  ·  sell Python dictionary copying, Making copies of Python dictionaries, Duplicating dictionaries in Python

Since a variable in Python is merely a label or reference to an object in the memory, a simple assignment operator will not create copy of object.

Example 1

In this example, we have a dictionary "d1" and we assign it to another variable "d2". If "d1" is updated, the changes also reflect in "d2".

 
d1 = {"a":11, "b":22, "c":33} d2 = d1 print ("id:", id(d1), "dict: ",d1) print ("id:", id(d2), "dict: ",d2) d1["b"] = 100 print ("id:", id(d1), "dict: ",d1) print ("id:", id(d2), "dict: ",d2)

Output

id: 2215278891200 dict: {'a': 11, 'b': 22, 'c': 33}
id: 2215278891200 dict: {'a': 11, 'b': 22, 'c': 33}
id: 2215278891200 dict: {'a': 11, 'b': 100, 'c': 33}
id: 2215278891200 dict: {'a': 11, 'b': 100, 'c': 33}

To avoid this, and make a shallow copy of a dictionary, use the copy() method instead of assignment.

Example 2

 
d1 = {"a":11, "b":22, "c":33} d2 = d1.copy() print ("id:", id(d1), "dict: ",d1) print ("id:", id(d2), "dict: ",d2) d1["b"] = 100 print ("id:", id(d1), "dict: ",d1) print ("id:", id(d2), "dict: ",d2)

Output

When "d1" is updated, "d2" will not change now because "d2" is the copy of dictionary object, not merely a reference.

id: 1586671734976 dict: {'a': 11, 'b': 22, 'c': 33}
id: 1586673973632 dict: {'a': 11, 'b': 22, 'c': 33}
id: 1586671734976 dict: {'a': 11, 'b': 100, 'c': 33}
id: 1586673973632 dict: {'a': 11, 'b': 22, 'c': 33}


The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back