Tuned
Tuned

Reputation: 11

Alternative to deepcopy in python

In a project we have to do for school, we got an assignment to write an implementation for the floyd-warshall algorithm. One of the restrictions was, that we could not use import statements. I had not read this and write my algorithm, using deepcopy. Now I am searching for a way to make my own sort of "copy" function.

The thing I want to copy is a dictionary of 2 dictionaries

{"a": {...}, "b": {...}}

Is this possible? thank you very much in advance

Upvotes: 1

Views: 1276

Answers (1)

Kasravnd
Kasravnd

Reputation: 107297

You can use a dict comprehension with copy method of dictionary :

d={"a": {...}, "b": {...}}

new={i:j.copy() for i,j in d.items()}

Demo :

>>> d ={1: {1: 5}, 2: {2: 2}, 3: {3: 9}}
>>> l ={i:j.copy() for i,j in d.items()}
>>> l[1][1]=0
>>> l
{1: {1: 0}, 2: {2: 2}, 3: {3: 9}}
>>> d
{1: {1: 5}, 2: {2: 2}, 3: {3: 9}}

Upvotes: 2

Related Questions