1
votes

There is lots of information on this in terms of one-liners that add one node/edge/attribute, but I am looking for loops or the like that allow me to assign 100 nodes (as well as edges eventually) with attributes.

For instance, having graph G, containing 100 nodes

I would like to give each node a value, but this doesn't work:

G = nx.Graph()
G.add_nodes_from(range(1,101))

G_node_atts = range(0,100)
G_na = nx.path_graph(G_node_atts)
G.add_edges_from(G_na.edges())

Resulting in:

G.nodes(data=True)
NodeDataView({0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 
... etc.

G.edges(data=True)
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {}), (3, 4, {}),
... etc.

And I would want node-attributes to look like:

[(1, {'id':0}),(2, {'id':1}), etc.]

Any help is greatly appreciated.

EDIT: the answer is quite helpful and returns the desired result. However, if I have several node-types, let's say nodes A, B and C, and I wish them all to contain attribute-values ranging from 0 to 3.

 ( {1: {'A': 0}, 2: {'A': 1}, 3: {'A': 2}, 4: {'A': 3} )
 ( {5: {'B': 0}, 6: {'B': 1}, 7: {'B': 2}, 8: {'B': 3} )
 ( {9: {'C': 0}, 10: {'C': 1}, 11: {'C': 2}, 12: {'C': 3} )

Do I need some sort of nested for loop?

(My overall goal is to have a somewhat large graph (maybe 400.000 nodes) that can contains several types of nodes (say 20) that through functions can grow edges between them (as well as attributes, edge-weight, etc.).)

1

1 Answers

0
votes

You can try the following:

G = nx.Graph()

for attr in range(100):
    G.add_node(attr+1, id=attr)

[edit] You can construct a directory like node_types = {1: 'A', 2: 'A', 3: 'A', ...} where each node has its kind, and then:

G = nx.Graph()

for attr in range(100):
    node = attr + 1
    G.add_node(node, node_type={node_types[node]: attr%4})