Goratra
Goratra

Reputation: 11

Pythonic ways to use sorted function

During the lockdown, I have been following a python course on coursera. To sort a dictionnary keys by values, they use the following syntax :

occurence = {'E': 2, 'F': 1, 'B': 2, 'A': 2, 'D': 3, 'I': 2, 'C': 1}

y = sorted(occurence.keys(), key=lambda k: occurence[k])

The code is working like a charm, but I got trouble to understand the "why" of the syntax. In the python documentation, to sort a list of tuples, they use this code :

student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

sorted(student_tuples, key=lambda student: student[2])

As I understand it, student allow us to iterate over the tuple student_tuples. But in the case of the dictionnary, the logic doesn't seems to be the same. As k is the iterable, we can't iterate through occurence.keys() which is just a list of key, and not the dictionnary itself.

To keep the same logic as the one in the documentation, i'll tend to go on something like :

items = sorted(occurence.items(), key = lambda k: k[1]) #  k iterate over occurence.items()
y = [key[0] for key in items]

Definitively longer, but it's not a mind twister anymore (to my eye !)

What do you think about that ? I'm just beginning my python journey, but I'm really concerned about the readability of my code.

Thanks !

Upvotes: 0

Views: 62

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

I think you missed one crucial point.

When you do sorted(iterable, key=func), the function needs to accept one argument which is the elements from iterable. The key is used by sorted to define the sorting criteria - when you don't want the default which is just the elements themselves. The key function is being called on each element from iterable internally, as part of the sorting algorithm.

So in the the tuples example, when you do sorted(student_tuples, key=lambda student: student[2]) This basically means "sort student_tuples according to the third element of each tuple". The arguments being passed to the lambda are the tuples, and from each tuple the third (index 2) element is used for comparing and deciding the order.

Back to the dict example, doing sorted(occurence.keys(), key=lambda k: occurence[k]) means: "sort the dict's keys, according to the value of each key in the dict". Again, in this case the iterable is the keys, so the arguments to the lambda are the keys themselves. The lambda then returns the value associated with each key by accessing the dict (occurence[k]) and that is used to compare and sort the keys.

Yes, lambda k: occurence[k] is a different and confusing pattern compared to the more "standard" lambda student: student[2], but that's part of learning - open yourself to new and challenging ways of using the tools a language has to offer.

Upvotes: 2

Related Questions