你最合适的方法是使用
nx.from_dict_of_dicts
。但它使用的字典格式略有不同。它使用一个只有单个'weight'元素的字典代替你拥有的权重数值:
{"E": 7} -> {"E": {"weight": 7}}
因此,您需要使用以下代码转换您的graph
字典:
import networkx as nx
graph = {
"A": {"B": 10, "C": 3},
"B": {"C": 1, "D": 2},
"C": {"B": 4, "D": 8, "E": 2},
"D": {"E": 7},
"E": {"D": 9}
}
# Convert integer weights to dictionaries with a single 'weight' element
gr = {
from_: {
to_: {'weight': w}
for to_, w in to_nodes.items()
}
for from_, to_nodes in graph.items()
}
G = nx.from_dict_of_dicts(gr, create_using=nx.DiGraph)
G.edges.data('weight')
输出:
OutEdgeDataView([
('D', 'E', 7),
('B', 'D', 2),
('B', 'C', 1),
('A', 'B', 10),
('A', 'C', 3),
('C', 'E', 2),
('C', 'B', 4),
('C', 'D', 8),
('E', 'D', 9)
])
P.S. gr
字典长这样:
{'A': {'B': {'weight': 10}, 'C': {'weight': 3}},
'B': {'C': {'weight': 1}, 'D': {'weight': 2}},
'C': {'B': {'weight': 4}, 'D': {'weight': 8}, 'E': {'weight': 2}},
'D': {'E': {'weight': 7}},
'E': {'D': {'weight': 9}}}
from_dict_of_dicts
或者只是nx.Graph(graph)
吗? - tomjnnx.Graph(graph)
没有捕获权重(据我所知使用vars(G)
),而from_dict_of_dicts
给出了TypeError: 'int' object is not iterable
。 - Robin Andrews