Home > OS >  Removing specific nodes and adjusting node number in a graph in Python
Removing specific nodes and adjusting node number in a graph in Python

Time:06-29

I have a list of nodes. I want to remove T from nodes and update the node number. The expected output is presented.

nodes={(0, 0): 1,
 (0, 1): 2,
 (0, 2): 3,
 (1, 0): 4,
 (1, 1): 5,
 (1, 2): 6,
 (2, 0): 7,
 (2, 1): 8,
 (2, 2): 9}

T=[(2, 0),(2,1)]

The expected output is

newnodes={(0, 0): 1,
 (0, 1): 2,
 (0, 2): 3,
 (1, 0): 4,
 (1, 1): 5,
 (1, 2): 6,
 (2, 2): 7}

CodePudding user response:

nodes={(0, 0): 1,
 (0, 1): 2,
 (0, 2): 3,
 (1, 0): 4,
 (1, 1): 5,
 (1, 2): 6,
 (2, 0): 7,
 (2, 1): 8,
 (2, 2): 9}

T=[(2, 0),(2,1)]

# For every node inside T
for t in T:

   # If the node exists inside nodes
   if (t in nodes):

      # Get the current index from the node
      index = nodes[t]

      # And remove the node from the dictionary
      nodes.pop(t)

      # Now, we update the indexes from nodes that were inserted after
      # node t
      for key in nodes:
         if (nodes[key] > index):
            nodes[key] -= 1

# Done
print(nodes)
  • Related