1

Having dictionary:

{'david': ['APP', 2], 'ala': ['PROD', 2], 'steven': ['DEV', 4], 'katya': ['SYS', 2]}

I want to sort it by prioritizing second element of list (descending) and then by first element of list (ascending). My desired output is:

>>> [('steven', ['DEV', 4]), ('david': ['APP', 2]), ('ala': ['PROD', 2]), ('katya': ['SYS', 2])]

The best idea i have:

x = sorted(x.items(), key=lambda elem: elem[1][1], reverse=True)
x.sort(key=lambda elem: elem[1][0])
>>> [('david', ['APP', 2]), ('steven', ['DEV', 4]), ('ala', ['PROD', 2]), ('katya', ['SYS', 2])]

Is there any function or approach from core python that would take into consideration sorting on the same object with values prioritizing, in my case if digits (digits are being sorted descending) are equal then look at strings like 'APP', 'DEV'... and sort them ascending by string?

Quasi31
  • 37
  • 5
  • 2
    Does this answer your question? [Sorting a Python list by two fields](https://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-fields) – sj95126 Oct 20 '21 at 21:14

1 Answers1

2

Use:

data = {'david': ['APP', 2], 'ala': ['PROD', 2], 'steven': ['DEV', 4], 'katya': ['SYS', 2]}


res = sorted(data.items(), key=lambda x: (x[1][1] * -1, x[1][0]))
print(res)

Output

[('steven', ['DEV', 4]), ('david', ['APP', 2]), ('ala', ['PROD', 2]), ('katya', ['SYS', 2])]

Multiplying by -1 will make the sorting descending on the second element.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76