Home > database >  Python Lambda Dictionary Sort
Python Lambda Dictionary Sort

Time:03-28

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.

CodePudding user response:

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.

  • Related