-3

How can I sort a list in ascending order without key matching?

Every key is unique and need sorting keys.

Input:

[{23: (1, 5)}, 
{59: (2, 3)}, 
{45: (2, 9)}, 
{28: (3, 6)}]

The output should be like this (Sorting based on keys of dict):

[{23: (1, 5)}, 
{28: (3, 6)},
{45: (2, 9)},
{59: (2, 3)}]
miradulo
  • 28,857
  • 6
  • 80
  • 93

1 Answers1

2

If your dictionaries always only have a single key then in Python 2.x:

print sorted([{23: (1, 5)}, {59: (2, 3)}, {45: (2, 9)}, {28: (3, 6)}])

Would give:

[{23: (1, 5)}, {28: (3, 6)}, {45: (2, 9)}, {59: (2, 3)}]

By default in Python 2.x using sorted() will result in a correctly sorted list.

For Python 3.x:

print(sorted([{23: (1, 5)}, {59: (2, 3)}, {45: (2, 9)}, {28: (3, 6)}], key=lambda x: next(iter(x))))

This uses a lambda function to extract the first (and only) key from the dictionary and use that as the sorting key.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97