2017-08-16 145 views
1

我对NetworkX documentation的阅读表明这应该起作用,但似乎没有?将NetworkX MultiDiGraph转换为字典或从字典中转换

考虑:

import networkx as nx 
g = nx.MultiDiGraph() 
g.add_nodes_from([0, 1]) 
g.add_edge(0,1) 
g.add_edge(0,1) 

g.edges() # returns [(0, 1), (0, 1)] 

d = nx.to_dict_of_dicts(g) # returns {0: {1: {0: {}, 1: {}}}, 1: {}} 

g2 = nx.from_dict_of_dicts(d, multigraph_input=True) 
# or, equivalently?, g2 = MultiDiGraph(d) 

g2.edges() # only returns [(0,1)] 

我在这里做一个简单的错误,或者这是一个错误?

对于我的应用程序,我发现了一个更好的选择,它使用networkx.readwrite.json_graph进行序列化,但我认为我会在这里留下问题以防其他人有用。

回答

1

问题是nx.from_dict_of_dicts()的默认图形输出看起来是一个简单的图形。

>>> g2 
<networkx.classes.graph.Graph at 0x10877add0> 

尝试创建同一类型的新的空图表为你想要哪个输出 - 因此,在你的情况下,MultiDiGraph。然后使用nx.from_dict_of_dicts()create_using参数,以确保新图是这种类型的:

>>> G = nx.MultiDiGraph() 
>>> g3 = nx.from_dict_of_dicts(d, multigraph_input=True, create_using=G) 
>>> g3.edges() 
[(0, 1), (0, 1)] 
>>> g3 
<networkx.classes.multidigraph.MultiDiGraph at 0x1087a7190> 

成功!

+0

非常好!非常感谢:)我会想'multigraph_input = True'会照顾到这一点,错过了'create_using' arg。 – Matthew