2

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.