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 ?
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.