to_dict_of_dicts#
- to_dict_of_dicts(G, nodelist=None, edge_data=None)[source]#
将图的邻接表示返回为字典的字典。
- 参数:
- 返回:
- 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
返回节点n
和nbr
之间每条边所需的边数据,给定现有边数据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}}