to_dict_of_dicts#
- to_dict_of_dicts(G, nodelist=None, edge_data=None)[source]#
- Returns adjacency representation of graph as a dictionary of dictionaries. - Parameters:
- Ggraph
- A NetworkX graph 
- nodelistlist
- Use only nodes specified in nodelist. If None, all nodes in G. 
- edge_datascalar, optional (default: the G edgedatadict for each edge)
- If provided, the value of the dictionary will be set to - edge_datafor all edges. Usual values could be- 1or- True. If- edge_datais- None(the default), the edgedata in- Gis used, resulting in a dict-of-dict-of-dicts. If- Gis a MultiGraph, the result will be a dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize handling edge data.- edge_datashould not be a container as it will be the same container for all the edges.
 
- Returns:
- doddict
- A nested dictionary representation of - G. Note that the level of nesting depends on the type of- Gand the value of- edge_data(see Examples).
 
 - See also - Notes - For a more custom approach to handling edge data, try: - dod = { n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()} for n, nbrdict in G.adj.items() } - where - customreturns the desired edge data for each edge between- nand- nbr, given existing edge data- dd.- Examples - >>> G = nx.path_graph(3) >>> nx.to_dict_of_dicts(G) {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}} - Edge data is preserved by default ( - edge_data=None), resulting in dict-of-dict-of-dicts where the innermost dictionary contains the edge data:- >>> 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 - If - edge_datais not- None, edge data in the original graph (if any) is replaced:- >>> 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 - This also applies to MultiGraphs: edge data is preserved by default: - >>> 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 - But multi edge data is lost if - edge_datais not- None:- >>> d = nx.to_dict_of_dicts(G, edge_data=10) >>> d {0: {1: 10}, 1: {0: 10}}