Skip to content Skip to sidebar Skip to footer

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 val

Solution 1:

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]

Solution 2:

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


    dict1 = {'A': 'can', 'B': 'Flower', 'C': 'house'}
    dict2 = {}
    forkeyin 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.

Solution 3:

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.

Post a Comment for "Create Deepcopy Of Dictionary Without Importing Copy"