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]
reversed_data.sort()
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.
Answer from Cyphase on Stack OverflowSorting lists in python: sorted() vs sort()
sorting - How does the key argument in python's sorted function work? - Stack Overflow
Can someone explain the `key=` argument for the sorted function
Sorted function in Python dictionary - Stack Overflow
Videos
Code: https://www.30secondsofcode.org/articles/s/python-sortedlist-vs-list-sort
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]
reversed_data.sort()
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.
>>> votes = {'Charlie': 20, 'Able': 10, 'Baker': 20, 'Dog': 15}
If we apply .items() on the votes dictionary above we get:
>>> votes_items=votes.items()
>>> votes_items
[('Charlie', 20), ('Baker', 20), ('Able', 10), ('Dog', 15)]
#a list of tuples, each tuple having two items indexed 0 and 1
For each tuple, the first index [0] are the strings ('Charlie','Able','Baker','Dog') and the second index [1] the integers (20,10,20,15).
print(sorted(votes.items(), key = lambda x: x[1])) instructs python to sort the items(tuples) in votes using the second index [1] of each tuple, the integers, as the basis of the sorting.
Python compares each integer from each tuple and returns a list that has ranked each tuple in ascending order (this can be reversed with the reverse=True argument) using each tuple's integer as the key to determine the tuple's rank,
Where there is a tie in the key, the items are ranked in the order they are originally in the dictionary. (so ('Charlie', 20) is before ('Baker', 20) because there is a 20==20 tie on the key but ('Charlie', 20) comes before ('Baker', 20) in the original votes dictionary).
The output then is:
[('Able', 10), ('Dog', 15), ('Charlie', 20), ('Baker', 20)]
I hope this makes it easier to understand.
Hi,
So I was doing a code challenge and it's about sorting a string in numerical order based on the integer as part of the string, e.g:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
I did it by creating a list with placeholder values and then assigned the values based on the number identified, see:
def order(sentence):
temp = sentence.split()
result = [0 for x in range(len(temp))]
for item in temp:
for char in item:
if char.isnumeric():
num = int(char)
result[num-1] = item
return " ".join(result)I was just looking at other solutions and saw this cool one liner:
return sorted(temp, key=lambda w:sorted(w))
But I don't quite understand how it works :(
I have used the key= argument in the past, for example sorting by the size of the string, i.e key=len
The lambda uses a variable, w and passes it through sorted, but how does that sort by the number included in the string?
You want to reverse the sort for x[1] only so don't pass reverse=True here, instead use negative number trick:
final = OrderedDict(sorted(mydict.items(), key=lambda x: (-x[1], x[0])))
{k: v for k, v in sorted(mydict.items(), key=lambda item: (-item[1], item[0]), reverse=False)}
Provided itemgetter(0) is O(1) when used with data, the sort is O(n log n) both on average and in the worst case.
For more information on the sorting method used in Python, see Wikipedia.
sorted is like sort except that the first builds a new sorted list from an iterable while sort do sort in place. The main difference will be space complexity.