问题
I am trying to run a neural gas network with an older script that doesn't work well with networkx 2 so I modified some things. However I am getting the error : Dictionary changed size during iteration and I don't get how to fix this because networkx is not my speciality. Any help?
The code that is causing the problem right now:
def prune_connections(self, a_max):
for u, v, attributes in self.network.edges(data=True):
if attributes['age'] > a_max:
self.network.remove_edge(u, v)
for u in self.network.nodes():
if self.network.degree(u) == 0:
self.network.remove_node(u)
and the error I am getting :
in __iter__
for nbr, dd in nbrs.items():
RuntimeError: dictionary changed size during iteration
回答1:
Here you're looping through the edges of the graph:
for u, v, attributes in self.network.edges(data=True):
But within that loop you modify the edges. So self.network.edges (which is fundamentally a dictionary) is changing while you're iterating. This isn't allowed by python.
A solution to this is to predefine
edgelist = list(self.network.edges(data=True))
then do
for u, v, attributes in edgelist:
来源:https://stackoverflow.com/questions/62321965/runtime-error-with-networkx-dictionary-changed-during-iteration-while-running