Q:

Python program to copy dictionaries

belongs to collection: Python Dictionary Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to get the keys of a dictionary... >>
<< Loop through a dictionary in Python...