Create nodes and edges with attributes and iterate over them

1,827 views
Skip to first unread message

KHALDOUN Mohsen

unread,
Mar 8, 2015, 12:46:10 PM3/8/15
to networkx...@googlegroups.com
Hello, how can I create nodes and edges with attributes and iterate over them.
nodes attributes are id and label.
edges attribute is weight.

I tried something like:

g = nx.Graph()
g.add_node(id=data[1], label=data[2])

g.add_edge(data[1], weight=data[2])


for g in G_list:
        for n in g.nodes():
            print("id:{} label{}".format(n[0],n[1]))                   
        for e in g.edges():
            print("{}---{}  x {}".format(e[0],e[1],e[2]))



but it say that:

tuple index out of range


Aric Hagberg

unread,
Mar 8, 2015, 12:48:58 PM3/8/15
to networkx...@googlegroups.com
The idiom I like is

for n,data in g.nodes(data=True):
print n,data
for u,v,data in g.edges(data=True):
print u,v,data

Aric
> --
> You received this message because you are subscribed to the Google Groups
> "networkx-discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to networkx-discu...@googlegroups.com.
> To post to this group, send email to networkx...@googlegroups.com.
> Visit this group at http://groups.google.com/group/networkx-discuss.
> For more options, visit https://groups.google.com/d/optout.

Don Mohsenuss

unread,
Mar 8, 2015, 1:04:06 PM3/8/15
to networkx...@googlegroups.com
And how can I put attributes in variable fro example weight (as a value not as a dictionnary )?

Daniel Schult

unread,
Mar 9, 2015, 6:09:03 PM3/9/15
to networkx...@googlegroups.com
With the latest prerelease version (github) you can use:

for n,data in g.nodes(data="node_weight"): 
    print n,data 
for u,v,data in g.edges(data="weight"): 
    print u,v,data 

With 1.9 and earlier versions use:

for n,data in g.nodes(data=True): 
    print n,data["node_weight"] 
for u,v,data in g.edges(data=True): 
    print u,v,data["weight"] 
Reply all
Reply to author
Forward
0 new messages