Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Lambda Dictionary Sort

The below code is sorting according to frequency of values and values are same it sorts the keys in descending order. How does the lambda within sort function work to achieve this?

c = Counter(nums)
nums.sort(key=lambda x: (c[x], -x))
return nums
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a lambda function:

key=lambda x: (c[x], -x)

It could also be written like this:

def key(x):
   return (c[x], -x)

When sort is called, it sends every element of the list to the lambda function, and uses the result of that function to determine what order the elements go in. In this case the lambda function takes in a number (x) and returns the value of x from the counter c, as well as the negative version of x in a tuple.

c = Counter([2,3,1,3,2])

Gives us this:

Counter({2: 2, 3: 2, 1: 1})

Now when every element of the original list is called individually against the lambda function, here’s what’s returned:

>>> for i in [2,3,1,3,2]:      
...     print(f"{i}: {key(i)}")
... 
2: (2, -2)
3: (2, -3)
1: (1, -1)
3: (2, -3)
2: (2, -2)

The column of tuples that you see is what’s being used by the sort function, because of the lambda function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading