Robin Andrews
Robin Andrews

Reputation: 3794

Weighted Adjacency List with Python Networkx

I have a graph defined in Python using the following structure:

graph = {
    "A": {"B": 10, "C": 3},
    "B": {"C": 1, "D": 2},
    "C": {"B": 4, "D": 8, "E": 2},
    "D": {"E": 7},
    "E": {"D": 9}
}

Is there some way to read this into networkx please?

I've tried G = nx.read_adjlist(graph) and looked at some of the json methods (https://networkx.github.io/documentation/stable/reference/readwrite/json_graph.html) but none seem to quite fit my use case.

Upvotes: 3

Views: 1524

Answers (1)

vurmux
vurmux

Reputation: 10020

The most appropriate method for you - nx.from_dict_of_dicts. But it uses slightly different dict format. Instead of the weight number you have, it uses a dictionary with a single 'weight' element:

{"E": 7} -> {"E": {"weight": 7}}

So you need to transform your graph dict with this code:

import networkx as nx

graph = {
    "A": {"B": 10, "C": 3},
    "B": {"C": 1, "D": 2},
    "C": {"B": 4, "D": 8, "E": 2},
    "D": {"E": 7},
    "E": {"D": 9}
}

# Convert integer weights to dictionaries with a single 'weight' element
gr = {
    from_: {
        to_: {'weight': w}
        for to_, w in to_nodes.items()
    }
    for from_, to_nodes in graph.items()
}

G = nx.from_dict_of_dicts(gr, create_using=nx.DiGraph)
G.edges.data('weight')

Output:

OutEdgeDataView([
('D', 'E', 7),
('B', 'D', 2),
('B', 'C', 1),
('A', 'B', 10),
('A', 'C', 3),
('C', 'E', 2),
('C', 'B', 4),
('C', 'D', 8),
('E', 'D', 9)
])

P.S. gr dict looks like this:

{'A': {'B': {'weight': 10}, 'C': {'weight': 3}},
 'B': {'C': {'weight': 1}, 'D': {'weight': 2}},
 'C': {'B': {'weight': 4}, 'D': {'weight': 8}, 'E': {'weight': 2}},
 'D': {'E': {'weight': 7}},
 'E': {'D': {'weight': 9}}}

Upvotes: 3

Related Questions