edge_subgraph fails for MultiDiGraph
Current Behavior
Attempting to create a subgraph induced by edges using edge_subgraph() of a MultiDiGraph fails with error:
File 'networkx\classes\function.py", line 452, in edge_subgraph
edges = set(edges)
TypeError: unhashable type: 'dict
Expected Behavior
Should create a subgraph view
Steps to Reproduce
Example of filtering a graph by edge data:
import networkx as nx
G = nx.MultiDiGraph()
G.add_nodes_from([1, 2])
G.add_edge(1, 2, None, kind='kind1', more_data='foo')
G.add_edge(1, 2, None, kind='kind2', even_more_data='bar')
sub_graph = G.edge_subgraph(
(u, v, d)
for u, v, d
in G.edges(data=True)
if d['kind'] == 'kind1'
)
Environment
Python version: 3.13.7 NetworkX version: 3.5
You should pass keys=True to edges as opposed to data=True. These subgraphs are constructed as views that "filter" the underlaying graph. So you don't need to pass the data, it is inferred from the underlying graph.
Just what @amcandio said -- and I'll add two other minor slightly subtle points:
G.edgeswithout any parentheses returns the(u, v, ekey)triples for multigraphs. So you could iterate over that if you weren't filtering on the data.G.edges(keys=True, data=True)iterates over the 4-tuples:(u, v, ekey, data). This is probably what you will need to be able to transmit the 3-tuples needed to identify the edge while using the edge data to filter the edge.
G = nx.MultiDiGraph()
G.add_nodes_from([1, 2])
G.add_edge(1, 2, None, kind='kind1', more_data='foo')
G.add_edge(1, 2, None, kind='kind2', even_more_data='bar')
sub_graph = G.edge_subgraph(
(u, v, k)
for u, v, k, d
in G.edges(keys=True, data=True)
if d['kind'] == 'kind1'
)
I have updated the edge_subgraph docstring to clarify the required edge formats as suggested by @amcandio and @dschult. Please have a look at the PR.