Reputation: 149
I'm trying to create a network graph in NetworkX based on a defeaultdict which contains nodes and edges. When I try to add the edges, I get the following error message:
add_edge() missing 1 required positional argument: 'v_of_edge'
My code is as follows:
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
G = nx.Graph()
for k,v in graph.items():
G.add_node(k)
G.add_edge(*v)
nx.draw()
plt.show()
I know that add_edge
takes (u,v)
argument, where I suppose that u
is node and v
is the edges, so instead I tried:
G.add_edge(k,v)
But that resulted in a new error message saying:
unhashable type: 'list'
I don't know how to proceed, but it leaves me at least one question. In the second approach, should I somehow access each edge for a given node individually?
Upvotes: 3
Views: 8462
Reputation: 1476
Here is a fix-up to your code that will make it work:
import networkx as nx
graph = {'a': ['c'], 'b': ['c', 'e'], 'c': ['a', 'b', 'd', 'e'], 'd': ['c'], 'e': ['c', 'b'], 'f': []}
G = nx.Graph()
for k,v in graph.items():
G.add_node(k)
for i in v:
G.add_edge(k, i)
nx.draw(G)
import matplotlib.pyplot as plt
plt.show()
As you can see, the main issue is that you need to properly add each edge. Since your v
are lists, you must go item by item in that list to add the edge.
Upvotes: 1
Reputation: 9008
The problem in your code is that v
is a list in your graph structure definition. The following code will make it work:
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
G = nx.Graph()
for k,v in graph.items():
for vv in v:
G.add_edge(k,vv)
nx.draw(G)
plt.show()
Based on your definition, you are supposed to loop through the list associated with each node to define the edge.
Upvotes: 5