當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python NetworkX to_dict_of_dicts用法及代碼示例

本文簡要介紹 networkx.convert.to_dict_of_dicts 的用法。

用法:

to_dict_of_dicts(G, nodelist=None, edge_data=None)

將圖形的鄰接表示作為字典的字典返回。

參數

G圖形

NetworkX 圖

nodelist列表

僅使用 nodelist 中指定的節點

edge_data標量,可選

如果提供,則所有邊的字典值將設置為edge_data。通常的值可以是 1 True 。如果edge_data None (默認值),則使用G 中的邊數據,從而生成dict-of-dict-of 字典。如果 G 是 MultiGraph,則結果將為 dict-of-dict-of-dict-of-dicts。有關自定義處理邊數據的方法,請參閱注釋。 edge_data 不應該是容器。

返回

doddict

G 的嵌套字典表示。請注意,嵌套級別取決於G 的類型和edge_data 的值(參見示例)。

注意

如需更自定義的處理邊數據的方法,請嘗試:

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

其中 customnnbr 之間的每個邊返回所需的邊數據,給定現有的邊數據 dd

例子

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

默認情況下保留邊數據(edge_data=None),導致 dict-of-dict-of-dicts 最裏麵的字典包含邊數據:

>>> 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}}

相關用法


注:本文由純淨天空篩選整理自networkx.org大神的英文原創作品 networkx.convert.to_dict_of_dicts。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。