How do I sort a zipped list in Python?

rectangletangle picture rectangletangle · Aug 22, 2011 · Viewed 48.8k times · Source

What's the Pythonic way to sort a zipped list?

code :

names = list('datx')
vals  = reversed(list(xrange(len(names))))
zipped = zip(names, vals)

print zipped

The code above prints [('d', 3), ('a', 2), ('t', 1), ('x', 0)]

I want to sort zipped by the values. So ideally it would end up looking like this [('x', 0), ('t', 1), ('a', 2), ('d', 3)].

Answer

Ulrich Dangel picture Ulrich Dangel · Aug 22, 2011

Quite simple:

sorted(zipped, key=lambda x: x[1])