TypeError: 'DiGraph' object does not support item assignment

Viewed 33

Context

While trying to set an attribute in a directional graph of in networkx, so not a node attribute but a graph attribute, I experienced the following error:

 File "/some_path/some_filepy", line 81, in add_result_to_last_graph
    snn_graphs[-1]["result"] = result_per_type
TypeError: 'DiGraph' object does not support item assignment

I did not quickly find an example on how to store attributes in a networkx graph in the documentation, so wondered:

Question

How can I store an attribute in a nx.DiGraph() object?

2 Answers

This issue has been encountered before by me, yet I did not find a specific solution for the networkx graph attribute setting in stackoverflow, so here is a way to store attributes in a nx.DiGraph object:

some_graph=nx.DiGraph()
some_attribute="pancakes"
# Store the attribute in the graph:
some_graph.graph["the_attribute_name"] = some_attribute

so in short, the syntax to store attributes in a graph, is: <graphname>.graph.

One can then print the graph attribute with:

print(some_graph.graph["the_attribute_name"])

Not sure if this is something that helps, but you could also instantiate the graph with the desired attribute:

from networkx import DiGraph
some_graph=DiGraph(some_attribute="pancakes")
some_graph.graph
# {'some_attribute': 'pancakes'}
Related