Q:

Python Dictionary Sorting Using Sorted

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?

A:

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.

