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