How to sort a list of tuples based on the first value i.e, in a dictionary we can use sorted(a.keys()).
How to do it for a list of tuples?
If these are the tuple values
t = [('2010-09-11', 'somedata', somedata),
('2010-06-11', 'somedata', somedata),
('2010-09-12', 'somedata', somedata)]
tuples should be sorted based on dates in the first field.
Usually, just
sorted(t)works, as tuples are sorted by lexicographical order. If you really want to ignore everything after the first item (instead of sorting tuples with the same first element by the following elements), you can supply akeythat picks out the first element. The simplest way would beoperator.itemgetter:Of course if you want to sort the list in-place, you can use
t.sort(key=operator.itemgetter(0))instead.