-2

Define:

diction = {"Book":(1, 2), "Armchair":(2, 2), "Lamp":(1, 3)}

If one wants to sort this dictionary by item["key"][1] descendingly and by "keys" ascendingly, what will be the appropriate way?

Desired output:

diction = {"Lamp":(1, 3), "Armchair":(2, 2), "Book":(1, 2)}

After receiving the correct answer by Sinan Note that I did not ask about sorting either ascendingly or descendingly, that you sent me the relevant links! I asked about doing both at the same time which is not solved by the trick of minus given by Sinan.

Fatimah
  • 105
  • 4
  • Does this answer your question? [How can I sort this dictionary with alphabetically?](https://stackoverflow.com/questions/15939732/how-can-i-sort-this-dictionary-with-alphabetically) – quamrana Feb 22 '20 at 22:38
  • Or this? https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key – Christian Feb 23 '20 at 00:12
  • None of them are asking my question, note that I asked about sorting both ascendingly and descendingly. The correct link and answer are given by @Sinan below. – Fatimah Feb 23 '20 at 20:50

1 Answers1

1

The main idea is copied from here.

from collections import OrderedDict
diction = {"Book":(1, 2), "Armchair":(2, 2), "Lamp":(1, 3)}
diction_list = list(diction.items())
diction = OrderedDict(sorted(diction_list, key=lambda x: (-x[1][1], x[0])))
print(diction)

OrderedDict([('Lamp', (1, 3)), ('Armchair', (2, 2)), ('Book', (1, 2))])

Here is where the magic is happening:

sorted(diction_list, key=lambda x: (-x[1][1], x[0]))

sorted sorts stuff for you. It is very good at it. If you use the key parameter with sort, you can give it a function to be used on each item to be sorted. In this case, we are giving at a lambda that returns the negative value from the tuples -x[1][1] (this is the second value in the tuple) and the key x[0]. The negative sign makes it sort in reverse. Of course, this would not work with non-numeric values.

The OrderedDict thing is not strictly necessary. Python keeps dict in order after version 3.6 I think (or was it 3.7?). OrderedDicts are always kept in the same order, so it is there that so our dict stays ordered independent of the Python version.

For a better way of doing this see the Sorting HOW TO in Python Documentation.

Sinan Kurmus
  • 585
  • 3
  • 11