-1

I have a question about this code in python.

xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

xm = sorted(xs.items(), key = lambda x : x[1])

print(xm)

I understand the sorted and items but that lambda I don't know how it works and why it works.

I need to order the dictionary from the value not from the keys.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

1

Why it works? So, you're using sorted function that accepts a function as second parameter. This parameter, in your case, is used for sorting by values, not by keys. Why?

xs.items() returns dict_items([('a', 4), ('b', 3), ('c', 2), ('d', 1)]) an object with array of tuples. When you use sorted(xs), sorted function looks inside the array and considers the first element of the tuple, in your case 'a', 'b', 'c', 'd'. It makes a sort looking this value, 'cause 'a' is less than 'b' and etc.

Let's consider another example, using xs with elements not sorted by key by default:

xs = {'b': 3, 'c': 2, 'a': 4, 'd': 1}

This one has xs.items() =

dict_items([('b', 3), ('c', 2), ('a', 4), ('d', 1)]

But, when you use sorted func you got:

>>> xm = sorted(xs.items())
>>> xm
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]

You sorted by the first element of the tuple.

So, this is the same of write:

xm = sorted(xs.items(), key=lambda x: x[0])

Alias = I wanna order the array xs.items() by its first element, also called key

But xs.items() also returns the value as second element of the tuple, so, if you write something like this (same of your code):

xm = sorted(xs.items(), key=lambda x: x[1])

you're saying: I wanna order the array xs.items() by its second element, also called value. The value of xs are: [3, 2, 4, 1] (in your case [4, 3, 2, 1]). So, it orders element following the rule of "less than". At the end of your code, you will see an array with, takes the tuple at place i, its second element, will be less than second element of the tuple i+1.


If you want the inverse, so, ordered by greater than, you could use the param reverse=True

santo
  • 418
  • 1
  • 3
  • 13
1

Ok, this is pretty simple.

Sorted tries to sort the collection based on some criteria.

  1. If it is a list strings, it does the string comparison wherein a comes before b and aa comes before ab.

  2. For list of int, 1 comes before 2 and so on.

In your case, you are passing, a dictionary. So, Python will try to sort them based on their keys value which is a string in this case. REMEMBER, when you do dict.items(), you get a list of tuples and item at 0th index is the key

So the below code will give the following result.

xs = {'a': 4, 'x': 3, 'z': 2, 'd': 1}
xm = sorted(xs.items())
print(xm)

OUTPUT -

[('a', 4), ('d', 1), ('x', 3), ('z', 2)]

Here you see that, a comes before d and d comes before x and z.

Now what if we don't want to use the default behaviour. Instead of using the key as the sorting criteria, we could use the value. In order for that to achieve, we need to tell the sorted function that fetch the values from tuples and then use them for comparision.

Following code does the same. lambda will receive the tuple as x and return x[1] which is the value in dictionary.

xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

xm = sorted(xs.items(), key = lambda x : x[1])

print(xm)

OUTPUT

[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Here, 1 comes before 2 and 3 and 4.

Now, if you update the lambda as lambda x : x[0], you are explicitly tell the sorted function to use the dict key as sorting criteria which is a default behavior

[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

xm = sorted(xs.items(), key = lambda x : x[0])

print(xm)

OUTPUT

[('a', 4), ('b', 3), ('c', 2), ('d', 1)] # same as before without the lambda
gsb22
  • 2,112
  • 2
  • 10
  • 25