转换 NetworkX MultiDiGraph to/from 字典
Converting a NetworkX MultiDiGraph to/from dictionaries
我对 NetworkX 的阅读 documentation 表明这应该有效,但似乎无效?
考虑:
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
进行序列化,但我想我会把问题留在这里以防它对其他人有用。
问题是 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>
成功!
我对 NetworkX 的阅读 documentation 表明这应该有效,但似乎无效?
考虑:
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
进行序列化,但我想我会把问题留在这里以防它对其他人有用。
问题是 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>
成功!