Python Networkx can't export to graphml with a

2019-08-08 08:10发布

问题:

Having the following problem converting a networkx graph to a graphml (can't post all the code here but here is the gist). NetworkX version is 1.6.2

I have a networkx digraph called G

G = nx.DiGraph()

Populate it with weighted edges from a list of authors in the format (AuthorA, AuthorB, Weight)

G.add_weighted_edges_from(author_list)

I can export the graphml here and it works fine

nx.write_graphml(G, 'test.graphml')

I then calculate the pagerank on the graph

graph_metric = nx.pagerank_numpy(G, weight='weight')

and then add attributes to the nodes in the graph

nx.set_node_attributes(G, 'pagerank', graph_metric)

if I iterate over the graph I can print out the node name and the pagerank

for n.d in G.nodes_iter(data=True):
     print n, d

AuthorA {u'pagerank': 0.0076688948270074164} ... ... ...

but if after updating the attributes I try to create a graphml from the graph I get the following error:

File "/usr/lib/pymodules/python2.7/networkx/readwrite/graphml.py", line 111, in generate_graphml

writer.add_graph_element(G)

File "/usr/lib/pymodules/python2.7/networkx/readwrite/graphml.py", line 305, in add_graph_element

self.add_nodes(G,graph_element)

File "/usr/lib/pymodules/python2.7/networkx/readwrite/graphml.py", line 262, in add_nodes

self.add_attributes("node", node_element, data, default)

File "/usr/lib/pymodules/python2.7/networkx/readwrite/graphml.py", line 255, in add_attributes

scope=scope, default=default_value)

File "/usr/lib/pymodules/python2.7/networkx/readwrite/graphml.py", line 242, in add_data

raise nx.NetworkXError('GraphML writer does not support '

NetworkXError: GraphML writer does not support dict types as data values.

Thoughts?

回答1:

well, it does tell you - you can't put a dictionary as a graphml attribute - they need to be either numeric types or strings, for the most part.

not the answer, but easier to put code here. find the 'bad' node:

for node in G.node:
    for attrib in G.node[node]:
        if type(G.node[node][attrib]) == dict:
            print node