1

I tried running this and I'm getting shortest path with memory address.How can I remove the memory address from the output

import networkx as nx
G=nx.Graph()
G.add_nodes_from([1,2,3,4])
G.add_weighted_edges_from([(1,2,8),(1,3,5),(2,4,1),(3,4,2)])
print(nx.floyd_warshall(G))

Here's the output

{1: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002AA0C397B70>, {1: 0, 2: 8, 3: 5, 4: 7}), 
`2: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002AA0D96A378>, {1: 8, 2: 0, 3: 3, 4: 1}),
3: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002425C098F28>, {1: 5, 2: 3, 3: 0, 4: 2}),
4: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002425C0A2048>, {1: 7, 2: 1, 3: 2, 4: 0})}

The output that I want is something like this-

1:{1:0, 2:8, 3:5, 4:7}
2:{1:8, 2:0, 3:3, 4:1}
3:{1:5, 2:3, 3:0, 4:2}
4:{1:7, 2:1, 3:2, 4:0}

2 Answers2

0

Looks like it's a dictionary inside a dictionary:

You can do something like this:

data = nx.floyd_warshall(G)

for key, value in data.iteritems():
    print('%s %s' % (key, value.values()))

Or if you want the key:value pair:

import json

data = nx.floyd_warshall(G)

for key, value in data.iteritems():
    print('%s %s' % (key, json.dumps(value)))
lapinkoira
  • 8,320
  • 9
  • 51
  • 94
0

It's printing out a dict of defaultdicts (which is what networkx returns), but you want it to print a dict of dicts, so you need to convert those defaultdicts into dicts.

X = nx.floyd_warshall(G)
Y = {a:dict(b) for a,b in X.items()}  
print(Y)
> {1: {1: 0, 2: 8, 3: 5, 4: 7},
 2: {1: 8, 2: 0, 3: 3, 4: 1},
 3: {1: 5, 2: 3, 3: 0, 4: 2},
 4: {1: 7, 2: 1, 3: 2, 4: 0}}
Community
  • 1
  • 1
Joel
  • 22,598
  • 6
  • 69
  • 93