Luis Cazares
Luis Cazares

Reputation: 77

How to order a list from dictionary values

I have a path list generated from Dijkstra algorithm and need to create another list indicating the position of the path, I already have the correct output but in a different order, how I can have the same order as my input.

boardPos   = [['F0','F1','F2','F3','F4'],
              ['E0','E1','E2','E3','E4'],
              ['D0','D1','D2','D3','D4'],
              ['C0','C1','C2','C3','C4'],
              ['B0','B1','B2','B3','B4'],
              ['A0','A1','A2','A3','A4']]

dijkstra = ['A2', 'B2', 'B1', 'B0', 'C0']

pos2Coord ={}
coordList = []

for iRow in range(len(boardPos)):
    for iCol in range(len(boardPos[iRow])):
        pos2Coord.update({boardPos[iRow][iCol] : (iRow, iCol)})

print (pos2Coord.items())
coordDict = {pk:pv for pk,pv in pos2Coord.items() if pk in dijkstra}
coordList = coordDict.values()
print (coordList)

Output:

pos2Coord:
[('D1', (2, 1)), ('A4', (5, 4)), ('A1', (5, 1)), ('E4', (1, 4)), ('B1', (4, 1)), 
 ('D4', (2, 4)), ('F0', (0, 0)), ('F1', (0, 1)), ('F2', (0, 2)), ('F3', (0, 3)), 
 ('F4', (0, 4)), ('E2', (1, 2)), ('E1', (1, 1)), ('E0', (1, 0)), ('B4', (4, 4)), 
 ('A0', (5, 0)), ('A3', (5, 3)), ('A2', (5, 2)), ('B0', (4, 0)), ('E3', (1, 3)), 
 ('B2', (4, 2)), ('B3', (4, 3)), ('C3', (3, 3)), ('C2', (3, 2)), ('C1', (3, 1)), 
 ('C0', (3, 0)), ('D2', (2, 2)), ('D3', (2, 3)), ('D0', (2, 0)), ('C4',(3, 4))]

coordList:
[(3, 0), (5, 2), (4, 0), (4, 1), (4, 2)]

the order I need is same as the Dijkstra position:

#['A2', 'B2', 'B1', 'B0', 'C0']    
[(5, 2), (4, 2), (4, 1), (4, 0), (3, 0)]

Upvotes: 2

Views: 38

Answers (1)

jpp
jpp

Reputation: 164613

This is one way.

res = sorted(coordDict.items(), key=lambda x: dijkstra.index(x[0]))
# [('A2', (5, 2)), ('B2', (4, 2)), ('B1', (4, 1)), ('B0', (4, 0)), ('C0', (3, 0))]

res_values = list(list(zip(*res))[1])
# [(5, 2), (4, 2), (4, 1), (4, 0), (3, 0)]

Explanation

  • sorted takes an argument key which accepts an anonymous (lambda) function.
  • Use sorted on your dictionary items, sorting on dijkstra's index level of your dictionary keys.
  • The result of sorted is a list of tuples sorted as required.
  • For res_values, unpack values by selecting the second element after unpacking via zip(*res).

Upvotes: 2

Related Questions