The shortest path algorithm using dictionaries [Python]

This is my first question, and for the first time I tried to do it, but I read the rules of the questions, and I hope that my question will correspond to all of them.

I have a project for my algorithm object, and it should create a gui for the shortest path dijkstra algorthim. I decided to use python because it is a language that I would like to learn. I have been trying for more than a week, and I always run into problems. But in any case, this is good fun :)!

I decided to present my oriented graph as a dictionary in this way:

g= {'A': {"B": 20, 'D': 80, 'G' :90}, # A can direct to B, D and G 'B': {'F' : 10}, 'F':{'C':10,'D':40}, 'C':{'D':10,'H':20,'F':50}, 'D':{'G':20}, 'G':{'A':20}, 'E':{'G':30,'B':50}, 'H':None} # H is not directed to anything, but can accessed through C 

therefore, the key is the top, and the value is the associated vets and weights. This is an example of a graph, but I planned to ask the user to enter their own graph data and study the shortest path between the two nodes [start β†’ end]. However, the problem is that I don’t even know how to access the internal dictionary, so I can work with the internal parameters, and I tried many ways like these two:

 for i in g: counter = 0 print g[i[counter]] # One print g.get(i[counter]) # Two 

but both give me the same result as: (Please note that I cannot access and play with internal parameters)

 {"B": 20, 'D': 80, 'G' :90} {'F' : 10} {'C':10,'D':40} {'D':10,'H':20,'F':50} {'G':20} {'A':20} {'G':30,'B':50} None 

So my question is: could you help me access the internal dictionaries so that I can start working on the algorithm itself. Thanks a lot in advance and thanks for reading.

+5
source share
3 answers

Using a for loop will iterate over the keys of the dictionary, and using the key you can get the value associated with the key. If the meaning itself is a dictionary, you can use a different loop.

 for fromNode in g: neighbors = g[fromNode] for toNode in neighbors: distance = neighbors[toNode] print("%s -> %s (%d)" % (fromNode, toNode, distance)) 

Note that for this you should use an empty dictionary {} instead of None when there are no neighbors.

+2
source

This is actually not that difficult and should make complete sense as soon as you see it. Take g . We want to get the weight of the 'B' connection from the 'A' node:

 >>> d = g['A'] >>> d {"B": 20, 'D': 80, 'G' :90} >>> d['B'] 20 >>> g['A']['B'] 20 

Using g['A'] , we get the key value in the dictionary g . We can directly affect this value by accessing the 'B' key.

+6
source

I think this gives you some ideas:

 for dict in g: print dict.get("B","") for dict in g: print dict.keys() #or dict.values() for dict in g: print dict["B"] 
+1
source

All Articles