Bala Prakash
Bala Prakash

Reputation: 31

Accessing attributes of nodes in a loop

I have the following list of nodes. I want to get the longitude and latitude of each node.

('11', {'Internal': 1, 'Latitude': -31.93333, 'Country': u'Australia', 'id': 11, 'Longitude': 115.83333, 'label': u'Perth1'})
('10', {'Internal': 1, 'Latitude': -35.28346, 'Country': u'Australia', 'id': 10, 'Longitude': 149.12807, 'label': u'Canberra2'})
('13', {'Internal': 1, 'Latitude': -34.93333, 'Country': u'Australia', 'id': 13, 'Longitude': 138.6, 'label': u'Adelaide1'})
('12', {'Internal': 1, 'Latitude': -31.93333, 'Country': u'Australia', 'id': 12, 'Longitude': 115.83333, 'label': u'Perth2'})
('15', {'Internal': 1, 'Latitude': -37.814, 'Country': u'Australia', 'id': 15, 'Longitude': 144.96332, 'label': u'Melbourne1'})
('14', {'Internal': 1, 'Latitude': -34.93333, 'Country': u'Australia', 'id': 14, 'Longitude': 138.6, 'label': u'Adelaide2'})
('17', {'Internal': 1, 'Latitude': -23.7, 'Country': u'Australia', 'id': 17, 'Longitude': 133.88333, 'label': u'Alice Springs'})
('16', {'Internal': 1, 'Latitude': -37.814, 'Country': u'Australia', 'id': 16, 'Longitude': 144.96332, 'label': u'Melbourne2'})

I know accessing like

G.nodes['11']['longitude']
G.nodes['10']['longitude']
G.nodes['13']['longitude'].

But I want flexible access which means no need to change the code if the number of nodes increases. How can I do that?

Upvotes: 1

Views: 82

Answers (2)

Abdallah Sobehy
Abdallah Sobehy

Reputation: 3021

The most compact way to iterate nodes is as follows:

for i in G:
    G.node[i]['longitude']

Upvotes: 3

Joel
Joel

Reputation: 23827

Just iterate through the nodes. The "best" way to iterate through the nodes is with G.nodes_iter() (a generator), but alternately you could use G.nodes() (a list):

import networkx as nx
G=nx.Graph()
G.add_node('11', longitude = 3)
for node in G.nodes_iter():
   print G.node[node]['longitude']
> 3
G.add_node('3', longitude = 5)
for node in G.nodes_iter():
    print G.node[node]['longitude']
>3
>5

If you care about the order that you go through the list, you'll want to use G.nodes() and sort it appropriately.


Note --- in your example you had G.nodes[][]. That won't work. It should be G.node[][].

Upvotes: 3

Related Questions