Cheese Cheese - 1 year ago 71
Python Question

How does the key argument in python's sorted function work?

Say I have

votes = {'Charlie': 20, 'Able': 10, 'Baker': 20, 'Dog': 15}

I understand

print(sorted(votes.items(), key = lambda x: x[1]))

will lead to

[('Able', 10), ('Dog', 15), ('Baker', 20), ('Charlie', 20)]`

But how does this work?

Answer Source

The function you pass in to key is given each of the items that are being sorted, and returns a "key" that Python can sort by. So, if you want to sort a list of strings by the reverse of the string, you could do this:

list_of_strings.sort(key=lambda s: s[::-1])

This lets you specify the value each item is sorted by, without having to change the item. That way, you don't have to build a list of reversed strings, sort that, then reverse them back.

# DON'T do this

data = ['abc', 'def', 'ghi', 'jkl']
reversed_data = [s[::-1] for s in data]
data = [s[::-1] for s in reversed_data]

# Do this

data.sort(key=lambda s: s[::-1])

In your case, the code is sorting each item by the second item in the tuple, whereas normally it would initially sort by the first item in the tuple, then break ties with the second item.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download