Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

networkx set node attributes from python dictionary

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?

like image 515
twfx Avatar asked Jan 29 '23 15:01

twfx


2 Answers

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)  
like image 159
dschult Avatar answered Feb 02 '23 10:02

dschult


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})]
like image 45
adnanmuttaleb Avatar answered Feb 02 '23 11:02

adnanmuttaleb