Reputation: 21
I am trying to play around with graphs on from networkx. I'm coding in python and have the necessary extensions. The code block is:
gr = {"0": ["4"],
"1": ["3"],
"2": ["2", "3", "4", "5"],
"3": ["1", "3"],
"4": ["3"],
"5": ["4"]
}
msg = nx.make_small_graph(gr)
but I receive this error:
Traceback (most recent call last):
File "C:\eclipse-workspace\graohToJSON\GraphToJSON.py", line 16, in
msg = nx.make_small_graph(gr) #Make Small Graph
File "C:\AppData\Local\Programs\Python\Python37-32\lib\site-packages\networkx\generators\small.py", line 90, in make_small_graph
ltype = graph_description[0]
KeyError: 0
Upvotes: 0
Views: 496
Reputation: 23827
I think Sparky05 has the best answer for you - namely that another command will handle the format you are trying to use (though I would recommend using ints instead of strings).
This answer explains what is wrong with the structure you've used.
From the documentation for make_small_graph
:
make_small_graph(graph_description, create_using=None)
graph_description
is a list of the form[ltype,name,n,xlist]
Here
ltype
is one of"adjacencylist"
or"edgelist"
,name
is the name of the graph andn
the number of nodes. This constructs a graph of n nodes with integer labels0,..,n-1
.If
ltype
="adjacencylist"
thenxlist
is an adjacency list with exactlyn
entries, in with the j’th entry (which can be empty) specifies the nodes connected to vertex j.... Use the
create_using
argument to choose the graph class/type.
So you've entered gr
, which is a dict, whose keys are strings. But it is expecting something very different: a list for which gr[0]
should either be "adjacencylist"
or "edgelist"
, and whose other elements give other information about the graph.
So you need to make your input be a list, whose first element tells it the format of your information about the graph structure. Then the second element of your list needs to be a name you are giving your graph. The next element needs to be the number of nodes in your graph. The final entry needs to either be a list of edges or a list of lists giving the nodes adjacent to each node.
So as I understand your intent, you want a directed graph (otherwise 4 would have an edge also to 0, not just 0 having an edge to 4):
gr = ['adjacencylist', 'my_graph', 6, [[4], [3], [2,3,4,5], [1,3], [3], [4]]]
G = nx.make_small_graph(gr, create_using = nx.DiGraph)
There are several specific examples shown in the documentation, so take a look at them.
Upvotes: 1
Reputation: 4882
You can simply create the (directed?) graph directly:
import networkx as nx
gr = {"0": ["4"],
"1": ["3"],
"2": ["2", "3", "4", "5"],
"3": ["1", "3"],
"4": ["3"],
"5": ["4"]
}
msg = nx.DiGraph(gr)
print(msg.edges)
# [('3', '3'), ('3', '1'), ('2', '4'), ('2', '3'), ('2', '2'), ('2', '5'), ('4', '3'), ('1', '3'), ('5', '4'), ('0', '4')]
Upvotes: 1