Sibghat Khan Sibghat Khan - 1 year ago 69
Python Question

Python Graph Changes

I have a Graph like this:

{'0': {'4': 1},
'1': {},
'2': {'3': 1, '4': 1},
'3': {'2': 1},
'4': {'0': 1, '2': 1}}

and I want to make some changes to it by removing a specific edge, but I also want to retain the original graph. So i use


to make a copy out of it. And then I run the function (on the new copy) which removes the specific edge that I want,( for example edge three which in this case is between node 2 and node 3 ) but What i get is that change also happens in the original Graph. How can I resolve this Issue ?

Furthermore, the Code which is used to remove an edge is this

def remove_links(graph_dic,edge_number):
count = 1
V,U = '',' '
for item in temp.items():
for node in item[1].items():
if count==edge_number:
V = item[0]
U = node[0]
del graph_dic[V][U]
return graph_dic

I don't want to have any changes in the original graph while also removing a specific edge that I want on the new copy. Furthermore, I'm running it on Jupyter Notebook...

Answer Source

but What i get is that change also happens in the original Graph

What you are doing is called: "Shallow copy". What you need to do is "Deep copy". You'd want to use: copy.deepcopy instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download