how to create nodes in networkx in python

To create nodes in Networkx, you simply need to call the add_node() function on a Graph object. Here's an example:

main.py
import networkx as nx

# Create an empty graph
G = nx.Graph()

# Add a single node to the graph
G.add_node(1)

# Add multiple nodes to the graph
G.add_nodes_from([2, 3, 4])

# Add nodes with attributes
G.add_node(5, color='red', size=10)

# Print the graph
print(G.nodes.data())
279 chars
17 lines

This will output:

main.py
[(1, {}), (2, {}), (3, {}), (4, {}), (5, {'color': 'red', 'size': 10})]
72 chars
2 lines

So we can see that each node is represented as a tuple, with the node ID as the first element and a dictionary of node attributes as the second element (which is empty if no attributes were given).

Note that you can also add nodes with edges at the same time using add_edge(), or add edges separately after adding nodes.

related categories

gistlibby LogSnag