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.
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)
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:
Program:
Output:
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:
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer