I am working with networkx and cant find a list of available attributes for edges or nodes anywhere. I am not interested in what attributes are assigned already, but what I can set/change when i create or edit the node or edge.
Can someone point me to where this is documented?
Thanks!
If you want to query a graph for all the possible attributes that might have been applied across the various nodes (and this, for communally created graphs, or ones that have been edited over time, is more common than you might imagine), then the following does the trick for me:
set(np.array([list(self.graph.node[n].keys()) for n in self.graph.nodes()]).flatten())
This returns all possible attribute names for which there are values attributed to graph-nodes. I've imported numpy as np
here in order to use np.flatten
for (relative) performance, but I'm sure there are various vanilla python alternatives (e.g. try the following itertools.chain
method, if you need to avoid numpy )
from itertools import chain
set(chain(*[(ubrg.graph.node[n].keys()) for n in ubrg.graph.nodes()]))
You can assign a lot of edge or node attributes when you create them. It's up to you to decide what their names will be.
import networkx as nx
G=nx.Graph()
G.add_edge(1,2,weight=5) #G now has nodes 1 and 2 with an edge
G.edges()
#[(1, 2)]
G.get_edge_data(2,1) #note standard graphs don't care about order
#{'weight': 5}
G.get_edge_data(2,1)['weight']
#5
G.add_node('extranode',color='yellow', age = 17, qwerty='dvorak', asdfasdf='lkjhlkjh') #nodes are now 1, 2, and 'extranode'
G.node['extranode']
{'age': 17, 'color': 'yellow', 'qwerty': 'dvorak', 'asdfasdf': 'lkjhlkjh'}
G.node['extranode']['qwerty']
#'dvorak'
Or you can use a dict to define some of the attributes with nx.set_node_attributes
and create a dict for all nodes for which a particular attribute is defined with nx.get_node_attributes
tmpdict = {1:'green', 2:'blue'}
nx.set_node_attributes(G,'color', tmpdict)
colorDict = nx.get_node_attributes(G,'color')
colorDict
#{1: 'green', 2: 'blue', 'extranode': 'yellow'}
colorDict[2]
#'blue'
Similarly there is a nx.get_edge_attributes
and nx.set_edge_attributes
.
More information is here in the networkx tutorial. About halfway down this page under the headings "Node Attributes" and "Edge Attributes". Specific documentation for the set...attributes
and get...attributes
can be found here under "Attributes".
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