Search code examples
pythonnetworkxkeyerror

KeyError "attr_dict" in NetworkX


This is my line of code. I keep getting KeyError: 'attr_dict'

edge_origins = [e[2]["attr_dict"]["Node1_reference"] for e in g.edges(data=True)]

This is a screenshot of the error:

enter image description here


Solution

  • In iterating over edges with data=True kwarg, the attr_dict will be present only if the edges have some data/attributes, otherwise, the dictionary will be empty.

    To make your code a bit more robust to this situation, you can use .get method:

    # note that this will return None for edges without data
    edge_origins = [e[2].get("attr_dict", {}).get("Node1_reference") for e in g.edges(data=True)]
    

    Here's a reproducible example:

    import networkx as nx
    
    G = nx.path_graph(3)
    G.add_edge(2, 3, weight=5)
    print([e[2].get("weight") for e in G.edges(data=True)])
    # [None, None, 5]