2
votes

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?

2
g.add_node('node1', attr_dict=optional_attrs) should do the job. You should read the documentation: networkx.github.io/documentation/stable/reference/generated/… - Simon Fromme
Also, argument names are taken literally. Even if you have a variable k the name of the argument you are passing to add_node will always be just the string "k". - Simon Fromme
ok. Looks like it creates a dict of dict. Thank you. - twfx

2 Answers

4
votes

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)  
1
votes

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})]