如何从格式为“节点:{邻居:权重}”的字典构造一个networkx图?

问题描述 投票:0回答:1

我有以下包含节点-邻居-权重对的字典:

graph = {
    "A": {"B": 3, "C": 3},
    "B": {"A": 3, "D": 3.5, "E": 2.8},
    "C": {"A": 3, "E": 2.8, "F": 3.5},
    "D": {"B": 3.5, "E": 3.1, "G": 10},
    "E": {"B": 2.8, "C": 2.8, "D": 3.1, "G": 7},
    "F": {"G": 2.5, "C": 3.5},
    "G": {"F": 2.5, "E": 7, "D": 10},
}

图表的直观表示是这样的:

enter image description here

如何从该字典转到

networkx
图形对象:

import networkx as nx

G = nx.Graph()

# YOUR SUGGESTION HERE #
python graph networkx graph-theory
1个回答
0
投票

使用字典理解的一种可能性和

from_dict_of_dicts

G = nx.from_dict_of_dicts({k: {n: {'weight': w} for n, w in d.items()}
                           for k,d in graph.items()})

输出图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.