0

I've got the following tuple of key, value pairs.

mytuple = (('2200', '10:00 PM'), ('2230', '10:30 PM'), ('2300', '11:00 PM'), ('2330', '11:30 PM'), ('0', '12:00 AM'), ('30', '12:30 AM'))

How would I sort this based on the key (i.e. time in 24 hour format)?

Jason Howard
  • 1,464
  • 1
  • 14
  • 43
  • Help here: https://www.pythoncentral.io/how-to-sort-a-list-tuple-or-object-with-sorted-in-python/ – jarmod Apr 30 '21 at 13:49
  • post your attempts code to sort – Wonka Apr 30 '21 at 13:51
  • 2
    `sorted(mytuple, key=lambda tpl: int(tpl[0]))` – Paul M. Apr 30 '21 at 13:51
  • How about... `sorted(mytuple)`. That would work if your keys really were in 24-hour format, but `'0'` and `'30'` are not in 24-hour format. – kaya3 Apr 30 '21 at 13:57
  • Does this answer your question? [How to sort a list/tuple of lists/tuples by the element at a given index?](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) – Tomerikoo Apr 30 '21 at 14:13

2 Answers2

0
print(sorted(mytuple, key=lambda x: int(x[0])))
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
vijaydeep
  • 395
  • 3
  • 12
0

An alternative that gives better performance:

import operator

print(sorted(mytuple, key=operator.itemgetter(0)))

For performance comparison, see this answer

Parzival
  • 2,051
  • 4
  • 14
  • 32