Skip to content
Advertisement

How to use key in the sort function in this situation (Python)?

I have a list like this:

l=[('a',2),('d',0),('c',1),('b',4)]

Now I want to sort it, but by the number, not by the word. If I just use l.sort() it just sorts by alphabetically. My desired output should be sth like (d,0)(c,1)(a,2)(b,4)

I tried l.sort(key = l[0][1]) but it won’t work too (l[0][1] actually refer to number 2, which is the second value)

Advertisement

Answer

You need to pass a lambda as the key that does the right thing:

>>> l = [("a", 2), ("d", 0), ("c", 1), ("b", 4)]
>>> l.sort(key=lambda val: val[1])
>>> l
[("d", 0), ("c", 1), ("a", 2), ("b", 4)]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement