1

I have a graph which has nodes/edges. I assigned the nodes some attributes

 [(1, {'node_rx_signal': 0}),
 (2, {'node_rx_signal': 0}),
 (3, {'node_rx_signal': 1}),
 (4, {'node_rx_signal': 0}),
 (5, {'node_rx_signal': 1}),
 (6, {'node_rx_signal': 0}),
 (7, {'node_rx_signal': 0}),
 (8, {'node_rx_signal': 0})]

e.g its is to signify that some nodes have this attribute set to 0 while others don't. With the help of for loop with an If condition I want to carry out a task but I can not seem to access the nodes with 'node_rx_signal' == 1.

nx.set_node_attributes(T1,values=0,name='node_rx_signal')
T1.nodes[3]['node_rx_signal'] = 1
T1.nodes[5]['node_rx_signal'] = 1  

for n, data in T1:
    if T1[n][data]==1:
        print(T1.node)
        print([n for n in T1.neighbors(n)])
    else:
        pass

Something along these lines.

RomainL.
  • 997
  • 1
  • 10
  • 24
f.nx
  • 13
  • 5

2 Answers2

1

Something along these lines I guess:

import networkx as nx

T1 = nx.Graph()
for i in range(1, 9):
    T1.add_node(i)

nx.set_node_attributes(T1, values=0, name='node_rx_signal')
nx.set_node_attributes(T1, values=0, name='node_visited')

T1.nodes[3]['node_rx_signal'] = 1
T1.nodes[5]['node_rx_signal'] = 1
T1.nodes[6]['node_visited'] = 1

for node, attr in T1.nodes(data=True):
    if attr['node_rx_signal'] == 1:
        print(node)
    if attr['node_visited'] == 1:
        print(node)

Prints:

3
5
6
Rafael
  • 7,002
  • 5
  • 43
  • 52
  • Thank you so much for your response. but in case my node has two attributes at the same time e.g [(1, {'node_rx_signal': 0},{'node_visited': 0}), 2.................] and can i access the same way but by using if attr['node_visited']==0 – f.nx Jan 28 '19 at 18:25
  • thank you so much for your prompt response. I am really grateful! – f.nx Jan 28 '19 at 18:38
0

so your question has already an answer, I really stress out that before posting you should always look by a google search!! looping through nodes and extract attributes in Networkx

in your case, a for loop calling for the nodes() method will do the trick son't forget the data=True if you are working with the attributes:

for my_node in T1.nodes(data=True):
     if my_node["node_rx_signal"] == 1:
          print(my_node)
RomainL.
  • 997
  • 1
  • 10
  • 24