NetworkX reverse for loop over nodes

Viewed 212

I am using NetworkX to create a DAG (directed acyclic graph). Each node is represented by an int with two different attributes 'operation' and 'reachable'. I am using the following 'for loop' to iterate over the node:

for nodes in p.nodes(data=True):
    ...

It goes over each node from the first to the last. In another part of the code, I need to iterate in the other way around, from last to first but I am not able to reverse the object as the type is <class 'networkx.classes.reportviews.NodeDataView'>. How is it possible to reverse the order of the for loop?

My network looks like this

[(1, {'operation': <qiskit.dagcircuit.dagnode.DAGNode object at 0x120a394d0>, 'reachable': False}), 
 (2, {'operation': <qiskit.dagcircuit.dagnode.DAGNode object at 0x120a39490>, 'reachable': False}),
 ..., 
 (12, {'operation': <qiskit.dagcircuit.dagnode.DAGNode object at 0x120a44250>, 'reachable': True})]
1 Answers

You can cast the NodeView object to a list, and then reverse the list.

g = nx.erdos_renyi_graph(100, 0.1)
node_list = list(g.nodes())
reversed_node_list = node_list[::-1]
Related