Adding a node with attribute in a NetworkX graph

Viewed 3381

The networkx tutorial hints the possibility of adding a node with attributes.

You can also add nodes along with node attributes if your container yields 2-tuples of the form (node, node_attribute_dict)

When I try it with the add_node method, I get a TypeError:

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_node(('person1', {'name': 'John Doe', 'age': 40}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/media/windows/Users/godidier/Projects/semlab/research/env/lib/python3.7/site-packages/networkx/classes/graph.py", line 506, in add_node
    if node_for_adding not in self._node:
TypeError: unhashable type: 'dict'

What am I missing ? or is adding nodes with attributes only possible with the add_nodes_from method ?

1 Answers

The right method in your case would be G.add_nodes_from

>>> G = nx.Graph()
>>> G.add_nodes_from([('person1', {'name': 'John Doe', 'age': 40})])
>>> G.nodes['person1']
{'name': 'John Doe', 'age': 40}

or also directly using add_node:

>>> G = nx.Graph()
>>> G.add_node('person1', name='John Doe', age=40)
>>> G.nodes['person1']
{'name': 'John Doe', 'age': 40}
Related