×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python program to copy dictionaries

Here, we are going to learn how to copy dictionaries in Python?
Submitted by Shivang Yadav, on March 24, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

There are some of the ways to copy dictionaries,

  1. Using the copy() method
  2. Using the dict() method

1) Copy dictionaries using the copy() method

The copy() method is a built-in method in Python, which can be used to create a copy of the dictionary.

Syntax:

dictionary2 = dictionary1.copy()

Program:

# Python program to copy dictionaries 
# using the copy() method

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# creating a copy 
dict_b = dict_a.copy()

# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)

print("Dictionary \'dict_b\' is...")
print(dict_b)

Output:

Dictionary 'dict_a' is...
{'age': 21, 'id': 101, 'name': 'Amit'}
Dictionary 'dict_b' is...
{'age': 21, 'id': 101, 'name': 'Amit'}

2) Copy dictionaries using the dict() method

The dict() method is a built-in method in Python, which is used to create a new dictionary and can also be used to create a copy of the dictionary by creating a new dictionary from an existing dictionary.

Syntax:

dictionary2 = dict(dictionary1)

Program:

# Python program to copy dictionaries 
# using the dict() method

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# creating a copy 
dict_b = dict(dict_a)

# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)

print("Dictionary \'dict_b\' is...")
print(dict_b)

Output:

Dictionary 'dict_a' is...
{'id': 101, 'name': 'Amit', 'age': 21}
Dictionary 'dict_b' is...
{'id': 101, 'name': 'Amit', 'age': 21}

Python Dictionary Programs »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.