5

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 Answer 1

9

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.