Reputation: 13
I tried to copy and paste an example from NetworkX package documentation. This is the example:
>>>G = nx.path_graph(5)
>>> path = nx.all_pairs_shortest_path(G)
>>> print(path[0][4])
[0, 1, 2, 3, 4]
Unfortunately, instead of the expected output, I get the following error message:
'generator' object has no attribute '__getitem__'
Upvotes: 1
Views: 940
Reputation: 23827
So your error is due to the fact that in Python 2.x many of the methods that used to return dicts now return generators. Among them is all_pairs_shortest_path
. You're using this new version of networkx, but looking at an out-of-date tutorial.
So the error message you saw comes from the fact that you have a generator path
and you're trying to access path[0]
, which doesn't make sense to Python. The easiest fix here is to simply follow the answer provided by Walter and say
path = dict(nx.all_pairs_shortest_path(G))
In general, when using code that was written for networkx 1.x, but you are using version 2.x, you should consult the migration guide (though in your case it's not particularly useful).
Upvotes: 2
Reputation: 21
Looks like path is a generator: convert it into a dictionary and it works:
path = dict(nx.all_pairs_shortest_path(G))
Upvotes: 1