简体   繁体   中英

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. ie...

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?

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 .

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] ie value and reversed it. Final result is list of tuples ie tuple[0] = key, tuple[1] = value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM