Nicholas Evans
Nicholas Evans

Reputation: 11

Create deepcopy of dictionary without importing copy

How can i create a deepcopy of a dictinoary without importing the deepcopy module? eg:

     dict = {'A' : 'can' , 'B' : 'Flower' , 'C' : 'house'}

I've tried assigning keys and values to 2 different lists and then creating a new dictionary with those values but that doesn't work. Any ideas?

Upvotes: 1

Views: 7085

Answers (3)

Trey Hunner
Trey Hunner

Reputation: 11814

It looks like you're using strings, which are immutable and therefore shouldn't need to be copied. So a deep copy probably isn't more useful than a shallow copy in your situation.

Here are two ways to do a shallow copy.

One way to copy a dictionary is to use its copy method:

my_dict = {'A' : 'can' , 'B' : 'Flower' , 'C' : 'house'}
another_dict = my_dict.copy()

Another is to pass the dictionary into the dict constructor:

my_dict = {'A' : 'can' , 'B' : 'Flower' , 'C' : 'house'}
another_dict = dict(my_dict)

You could also use a dictionary comprehension, but that's essentially the same thing using the dict constructor in many more characters.

Upvotes: 0

Selcuk
Selcuk

Reputation: 59228

Your example does not require deepcopy as it does not have any nested dicts. For a shallow copy, you can use a dictionary comprehension:

>>> dict1 = {'A' : 'can' , 'B' : 'Flower' , 'C' : 'house'}
>>> dict2 = {key: value for key, value in dict1.items()}
>>> dict2
{'A': 'can', 'C': 'house', 'B': 'Flower'}

However this method will not accomplish a deepcopy:

>>> dict1 = {'A' : []}
>>> dict2 = {key: value for key, value in dict1.items()}
>>> dict2['A'].append(5)
>>> dict1['A']
[5]

Upvotes: 1

Right leg
Right leg

Reputation: 16720

In addition to the answer from Selcuk, you could simply do:


    dict1 = {'A': 'can', 'B': 'Flower', 'C': 'house'}
    dict2 = {}
    for key in dict1 :
        dict2[key] = dict1[key]
    

However, this example is pretty trivial, and if you happened to have objects instead of strings, you would have to re-implement a `deepcopy` function by yourself.

Upvotes: 0

Related Questions