Reputation: 23
This is a newbie question for which I could not find a precise answer for. I would like to sort a dictionary in descending order according to the values. i.e....
dict = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5}
I know that this works...
>>> sorted(dict.items(), key=lambda x: x[1], reverse=True)
[('tom', 21), ('eddie', 12), ('ann', 9), ('fred', 5)]
But I am trying to understand how this part works...
x: x[1]
How is this matching the value attribute?
Upvotes: 2
Views: 95
Reputation: 16940
Let me explain whats going on:
Your dictionary:
d = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5}
Here is what sorted usage help says:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
Lets break down :
From your snipet: sorted(dict.items(), key=lambda x: x[1], reverse=True)
iterable : d.items()
which is list of tuples,
>>> d.items()
[('ann', 9), ('fred', 5), ('eddie', 12), ('tom', 21)]
>>>
key = lambda x: x[1]
NB: key parameter to specify a function to be called on each list element prior to making comparisons.
Lets apply to your case:
>>> key = lambda x: x[1]
>>> map(key, d.items())
[9, 5, 12, 21]
>>>
Which gave the values of the dictionary.
reverse=True showing below, hope you can understand easily from the example.
>>> l = [3,2,4,1]
>>> sorted(l)
[1, 2, 3, 4]
>>> sorted(l, reverse=True)
[4, 3, 2, 1]
>>>
conclusion:
You are reversing a dictionary based on value d[1]
i.e value and reversed it.
Final result is list of tuples i.e tuple[0] = key, tuple[1] = value.
Upvotes: 0
Reputation: 1122252
dict.items()
returns a list of (key, value)
pairs, x[1]
is simply the value
part of that pair:
>>> d = {'ann': 9, 'tom': 21, 'eddie': 12, 'fred': 5}
>>> d.items()
[('ann', 9), ('fred', 5), ('eddie', 12), ('tom', 21)]
>>> d.items()[0]
('ann', 9)
>>> d.items()[0][1]
9
>>> (lambda x: x[1])(d.items()[0])
9
sorted()
passes each element in the input sequence (so ('ann', 9)
, etc.) into the key
function. x
is then ('ann', 9)
and x[1]
is 9
.
Upvotes: 1