Soumya
Soumya

Reputation: 127

Cannot Write Graph with attributes in graphml format in networkx

I am trying to export my directed graph into graphml format in networkx. here is the graph code in networkx and the error i am getting:

h = nx.path_graph(5)

G.add_nodes_from(h)

G.add_edges_from(h.edges()

G[0]['name']="panama"

G[1]['name']="costa rica"

G[2]['name']="Argentina"

G[3]['name']="Brazil"

G[4]['name']="Coloumbia"

G[1][2]['connection']='road'

nx.write_graphml(G,"te.graphml")

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in write_graphml
  File "/usr/local/lib/python2.7/dist-packages/networkx/utils/decorators.py", line 220, in _open_file
    result = func(*new_args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 82, in write_graphml
    writer.add_graph_element(G)
  File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 351, in add_graph_element
    self.add_edges(G,graph_element)
  File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 325, in add_edges
    self.add_attributes("edge", edge_element, data, default)
  File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 297, in add_attributes
    for k,v in data.items():
AttributeError: 'str' object has no attribute 'items'

Upvotes: 1

Views: 2435

Answers (1)

Aric
Aric

Reputation: 25299

You are allowed to make assignments to arbitrary internal NetworkX data structures but in this case you are doing the assignment incorrectly (and it breaks the data structure).

You have

h = nx.path_graph(5)
G.add_nodes_from(h)
G.add_edges_from(h.edges()
G[0]['name']="panama" <--- this corrupts the adjacency data structure

use

G.node[0]['name']='panama'

to assign data to nodes.

Upvotes: 2

Related Questions