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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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
thank you so much for your prompt response. I am really grateful!
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)

3 Comments

The syntax is wrong. G.nodes(data=True) returns a tuple.
I had tried this earlier but the error was the same
what version of networkx are you using? Could you provide an example networks?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.