Home > Enterprise >  Networkx - ValueError: not enough values to unpack (expected 3, got 2)
Networkx - ValueError: not enough values to unpack (expected 3, got 2)

Time:07-03

I encountered this error when setting the attribute values for the networkx.MultiDiGraph instance G. I am using the set_edges_attributions method. The code is as follows.

# a lib I wrote myself
import dijkstra

for edge in G.edges():
    w = dijkstra.cost_cal(G, edge[0]) 
    print(w, edge)
    
    # G: networkx.MultiDiGraph
    # edge: a tuple with two node IDs
    # w: float
    nx.set_edge_attributes(G, {edge: {"cost": w}})

Out:

0.05050505050505051 (1004215022, 1955253358)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [6], in <cell line: 6>()
      7 w = dijkstra.cost_cal(G, edge[0]) 
      8 print(w, edge)
----> 9 nx.set_edge_attributes(G, {edge: {"cost": w}})

File C:\ProgramData\Miniconda3\envs\PyGIS\lib\site-packages\networkx\classes\function.py:821, in set_edge_attributes(G, values, name)
    818 else:
    819     # `values` consists of doct-of-dict {edge: {attr: value}} shape
    820     if G.is_multigraph():
--> 821         for (u, v, key), d in values.items():
    822             try:
    823                 G[u][v][key].update(d)

ValueError: not enough values to unpack (expected 3, got 2)

CodePudding user response:

You are not giving the correct edge format to MultiDiGraph

So you need to use:

nx.set_edge_attributes(G, {('a', 'b', 0): {'cost': 42}})

But you likely only used:

nx.set_edge_attributes(G, {('a', 'b'): {'cost': 42}})

Note that, unlike G.edges, G.edges() doesn't output the key:

OutMultiEdgeDataView([('a', 'b'), ('a', 'b'), ('a', 'c')])

So use G.edges in your loop.

  • Related