to_dict_of_dicts#

to_dict_of_dicts(G, nodelist=None, edge_data=None)[source]#

将图的邻接表示返回为字典的字典。

参数:
G

一个 NetworkX 图

nodelist列表

仅使用 nodelist 中指定的节点

edge_data标量,可选

如果提供,字典的值将对于所有边设置为 edge_data。常见值可以是 1True。如果 edge_dataNone(默认),则使用 G 中的边数据,结果将是字典的字典的字典。如果 G 是 MultiGraph,结果将是字典的字典的字典的字典。有关自定义处理边数据的方法,请参见 Notes。edge_data 应是容器。

返回:
dod字典

G 的嵌套字典表示形式。注意,嵌套级别取决于 G 的类型和 edge_data 的值(参见 Examples)。

注意

对于更自定义的处理边数据的方法,请尝试

dod = {
    n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()}
    for n, nbrdict in G.adj.items()
}

其中 custom 返回节点 nnbr 之间每条边所需的边数据,给定现有边数据 dd

示例

>>> G = nx.path_graph(3)
>>> nx.to_dict_of_dicts(G)
{0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}}

默认情况下(edge_data=None)保留边数据,结果是字典的字典的字典,其中最内层字典包含边数据

>>> G = nx.Graph()
>>> G.add_edges_from(
...     [
...         (0, 1, {"weight": 1.0}),
...         (1, 2, {"weight": 2.0}),
...         (2, 0, {"weight": 1.0}),
...     ]
... )
>>> d = nx.to_dict_of_dicts(G)
>>> d  
{0: {1: {'weight': 1.0}, 2: {'weight': 1.0}},
 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}},
 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}}
>>> d[1][2]["weight"]
2.0

如果 edge_data 不是 None,则原始图中的边数据(如果有)将被替换

>>> d = nx.to_dict_of_dicts(G, edge_data=1)
>>> d
{0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}}
>>> d[1][2]
1

这也适用于 MultiGraphs:默认保留边数据

>>> G = nx.MultiGraph()
>>> G.add_edge(0, 1, key="a", weight=1.0)
'a'
>>> G.add_edge(0, 1, key="b", weight=5.0)
'b'
>>> d = nx.to_dict_of_dicts(G)
>>> d  
{0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}},
 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}}
>>> d[0][1]["b"]["weight"]
5.0

但如果 edge_data 不是 None,则多重边数据将丢失

>>> d = nx.to_dict_of_dicts(G, edge_data=10)
>>> d
{0: {1: 10}, 1: {0: 10}}