Avoid deepcopy() in Python when changing dictionary
As @dmargol1 suggested in the comments, I was able to avoid deepcopy() and copy() by instead building the graph from scratch, rather than copying and modifying it, which was actually a lot faster.
If that is possible: do it!
If copying is neccessary, there are two ways. If you don't need to alter the values, copy() is the way to go, since it is a lot faster than deepcopy() (see the comment of @george-solymosi). If alteration of the values is needed, deepcopy is the only way (see the comment of @gall).
I am looking for a solution to avoid deepcopy() in my task using Python.
I am implementing a statistical dependency parser using chu-liu-edmonds algorithm. I have a graph represented as a dictionary with every head node stored as a key with each having a list containing one or more objects of the class arc as the value.
In the cle-algorithm, I need to modify the graph (contract a cycle). That means, that I need to delete arc objects and heads, and add others, while I later need the original graph to expand those contracted cycles. Right now, I achieve this by deepcopying the original graph and pass it to the contract function.
Now I ran my programm with cProfile and found out that everything that has to do with deepcopy is by far the part of the algorithm that takes the most time.
So my question is: Is there any way to avoid/reduce this in my situation?