How can I create a graph node with additional attributes using a dictionary

364 views Asked by At

Tried creating a graph like this:

import networkx as nx
from datetime import datetime

#create undirected graph g
g = nx.Graph()
#add nodes
g.add_node("John", {"name":"John", "age":25})
g.add_node("Peter", {'name': 'Peter', 'age':35})
g.add_node("Mary", {'name': 'Mary', 'age':31})
g.add_node("Lucy", {'name': 'Lucy', 'age':19})
#add edges
g.add_edge("John", "Mary", {'Since': datetime.today()})
g.add_edge("John", "Peter", {'Since': datetime(1990, 7, 30)})
g.add_edge("John", "Mary", {'Since': datetime(2010,8, 10)})

print(g.nodes())
print(g.edges())
print(g.has_edge("Lucy", "Mary"))

ERROR: TypeError: add_node() takes 2 positional arguments but 3 were given

Any idea how to fix this??

1

There are 1 answers

1
CDJB On

This can be done by prepending the attribute dictionaries with **. See the docs here for more details.

import networkx as nx
from datetime import datetime

#create undirected graph g
g = nx.Graph()
#add nodes
g.add_node("John", **{"name":"John", "age":25})
g.add_node("Peter", **{'name': 'Peter', 'age':35})
g.add_node("Mary", **{'name': 'Mary', 'age':31})
g.add_node("Lucy", **{'name': 'Lucy', 'age':19})
#add edges
g.add_edge("John", "Mary", **{'Since': datetime.today()})
g.add_edge("John", "Peter", **{'Since': datetime(1990, 7, 30)})
g.add_edge("John", "Mary", **{'Since': datetime(2010,8, 10)})

print(g.nodes())
print(g.edges())
print(g.has_edge("Lucy", "Mary"))

Output:

['John', 'Peter', 'Mary', 'Lucy']
[('John', 'Mary'), ('John', 'Peter')]
False
>>> g.nodes['John']
{'name': 'John', 'age': 25}