I'm trying to write a general function which creates a graph that takes a list of nodes and edges. For each node, there's a set of default attributes, and a set of optional attributes. As the optional attributes can be anything, I'm thinking to use a dictionary to store them. However, it looks like add_node() doesn't seems to accept a variable as keyword. Given the below code snippet,
import networkx as nx
optional_attrs = {'ned':1, 'its':'abc'}
g = nx.Graph()
g.add_node('node1')
for k, v in optional_attrs.iteritems():
g.add_node('node1', k=v)
print g.node(data=True)
I get
NodeDataView({'node1':{'k':'abc'}})
Instead of,
NodeDataView({'node1':{'ned':1, 'its':'abc'}})
I wonder it is possible to achieve that?
In general in python if you want to use a dict
to provide keyword arguments to a function you prepend the dict with **
.
g.add_node('node1', **optional_attrs)
You can also add/change node attributes after adding the nodes:
g.add_node('node1')
g.nodes['node1'].update(optional_attrs)
You can also use the set_node_attributes function, which takes a graph and a dictionary. the keys set of the dic is a subset of the nodes of the graph and its values are data of their corresponding keys.
import networkx as nx
optional_attrs = {'node1':{'ned':1, 'its':'abc'}}
g = nx.Graph()
g.add_node('node1')
nx.set_node_attributes(g, optional_attrs)
print(g.nodes.data())
this will output:
[('node1', {'its': 'abc', 'ned': 1})]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With