I am unable to create a "duplicate" dictionary in the program
below is the sample code
dict1={'name':'rahul',age:30}
i need to create a dictionary with two entries.
I am unable to create a "duplicate" dictionary in the program
below is the sample code
dict1={'name':'rahul',age:30}
i need to create a dictionary with two entries.
In Python, there are two ways to create copies :
In order to make these copy, you can use the copy
module.
For Example:
import copy
dict1={'name':'rahul', 'age': 30}
# Shallow copy
dict2 = copy.copy(dict1)
# Deep Copy
dict3 = copy.deepcopy(dict1)
If you don't know the difference between shallow copy
and deep copy
please check this very good article: https://docs.roguewave.com/sourcepro/11.1/html/toolsug/6-4.html
I find this image essential in understanding the concept:
You're missing the quotes around age
:
dict1={'name':'rahul', 'age':30}
Do you mean copying a dictionary? You have two options:
Shallow Copy
Deep Copy
Check this link: https://thispointer.com/python-how-to-copy-a-dictionary-shallow-copy-vs-deep-copy/
In python dictionary both key and value should be Enclosed with double Quotes or Single Quotes if the value is a string.
You can't assign a value to a key like assigning value to a variable
Example:
In dictionary you should assign as 'age':30
If 'age' is a variable that you are declaring outside the dictionary then you can assign as
age = 30
Coming back to your Question did you mean copying a dictionary or just create a duplicate like this
dict1={'name':'rahul','age':30}
dict2={'name':'rahul','age':30}
print(dict1)
print(dict2)
if you need to know how to copy a dictionary refer this article https://www.science-emergence.com/Articles/How-to-copy-a-dictionary-in-python-/