Reputation: 69
I have a python list with user ids
data = [123,456,789]
and I want to sort this list based on how many points they have (calculated by points[userid]). I have tried SortedData = sorted(data,key=points,reverse=True)
to no avail. Is there any way to do this?
Thanks. Evan
Upvotes: 0
Views: 47
Reputation: 5012
key
also accepts a function.
Try this:
sorted_list = list(sorted(data, key= lambda userid: points[userid], reverse=True))
Upvotes: 0
Reputation: 54168
You need to epxlicit it in a lambda
. You could di points[x]
but points.get(x,0)
may be safer here
data = [123,456,789]
points = {123:20, 456:10, 789:15}
sortedData = sorted(data, key=lambda x:points.get(x,0), reverse=True)
print(sortedData)
If you're ok of letting None
as default value instead of a number, you can reduce to
sortedData = sorted(data, key=points.get, reverse=True) # use the method itself
Upvotes: 2