You can use Counter
to count the number of duplicate edges in order to generate weight that is passed to DiGraph
:
import networkx as nx
from collections import Counter
EDGES = [
('A', 'B'),
('B', 'C'),
('A', 'C'),
('C', 'D'),
('A', 'B')
]
g = nx.DiGraph((x, y, {'weight': v}) for (x, y), v in Counter(EDGES).items())
print(*g.edges(data=True), sep='\n')
Output:
('A', 'B', {'weight': 2})
('A', 'C', {'weight': 1})
('C', 'D', {'weight': 1})
('B', 'C', {'weight': 1})
In above Counter
returns (edge, count)
tuples. Note that edges passed to Counter
must be hashable.
>>> edges = list(Counter(EDGES).items())
>>> edges
[(('A', 'B'), 2), (('B', 'C'), 1), (('C', 'D'), 1), (('A', 'C'), 1)]
Then generator expression is used to yield edges in a format that DiGraph
expects:
>>> params = list((x, y, {'weight':v}) for (x,y), v in edges)
>>> params
[('A', 'B', {'weight': 2}), ('B', 'C', {'weight': 1}), ('C', 'D', {'weight': 1}), ('A', 'C', {'weight': 1})]