1

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.

Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
  • What do you mean with "duplicate"? – Paolo Mossini Mar 02 '20 at 07:24
  • `dict2 = dict(dict1)`? or https://docs.python.org/3/library/copy.html?highlight=deepcopy#copy.deepcopy ? https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy . what have you tried? – hiro protagonist Mar 02 '20 at 07:24
  • @sudarshang is `age` a variable referencing a string? I think you might want to put ticks around the word "age". Might be helpful too if you could say what the error message is that you're seeing. – Todd Mar 02 '20 at 07:59

4 Answers4

3

In Python, there are two ways to create copies :

  • Shallow copy
  • Deep copy

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:

enter image description here

V. Sambor
  • 12,361
  • 6
  • 46
  • 65
1

You're missing the quotes around age:

dict1={'name':'rahul', 'age':30}
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
1

Do you mean copying a dictionary? You have two options:

  1. Shallow Copy

  2. Deep Copy

Check this link: https://thispointer.com/python-how-to-copy-a-dictionary-shallow-copy-vs-deep-copy/

RAJ JOHRI
  • 31
  • 5
1

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-/

j s
  • 187
  • 8