2017-08-16 300 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