1

I have a social network graph 'G'.

I'm trying to check that they keys of my graph are in the characteristics dataset as well. I ran this command:

for node in G.nodes():
    if node in caste1.keys():
        pass
    else:
        G = G.remove_node(node)

It shows an error RuntimeError: dictionary changed size during iteration

Cainã Max Couto-Silva
  • 4,839
  • 1
  • 11
  • 35
kr1010
  • 27
  • 1
  • 7
  • 1
    Removing a node during iteration is going to change the size of your dictionary. It looks like this might help you https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating – EnigmaticBacon Dec 10 '20 at 00:51

1 Answers1

1

The RuntimeError is self-explanatory. You're changing the size of an object you're iterating within the iteration. It messes up the looping.

What you can do is to first iterate across the nodes to get the ones you would like to remove, and store it in a separate variable. Then you can iterate with this variable to remove the nodes:

# Identify nodes for removal
nodes2remove = [node for node in G.nodes() if node not in caste1.keys()]

# Remove target-nodes
for node in nodes2remove:
    G = G.remove_node(node)
Cainã Max Couto-Silva
  • 4,839
  • 1
  • 11
  • 35