Storing and Accessing node attributes python networkx

As you say, it’s just a matter of adding the attributes when adding the nodes to the graph

G.add_node('abc', dob=1185, pob='usa', dayob='monday')

or as a dictionary

G.add_node('abc', {'dob': 1185, 'pob': 'usa', 'dayob': 'monday'})

To access the attributes, just access them as you would with any dictionary

G.node['abc']['dob'] # 1185
G.node['abc']['pob'] # usa
G.node['abc']['dayob'] # monday

You say you want to look at attributes for connected nodes. Here’s a small example on how that could be accomplished.

for n1, n2 in G.edges_iter():
    print G.node[n1]['dob'], G.node[n2]['dob']
    print G.node[n1]['pob'], G.node[n2]['pob']
    # Etc.

As of networkx 2.0, G.edges_iter() has been replaced with G.edges(). This also applies to nodes. We set data=True to access attributes. The code is now:

for n1, n2 in list(G.edges(data=True)):
    print G.node[n1]['dob'], G.node[n2]['dob']
    print G.node[n1]['pob'], G.node[n2]['pob']
    # Etc.

NOTE: In networkx 2.4, G.node[] has been replaced with G.nodes[].

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)