17

I need sort this list of dictionaries:

[ {K: 1, B: 2, A: 3, Z: 4, ... } , ... ] 

Ordering should be:

  • K - descending
  • B - descending
  • A - ascending
  • Z - ascending

I only found out how to sort all keys in ascending or descending (reverse=True):

stats.sort(key=lambda x: (x['K'], x['B'], x['A'], x['Z']))

Can anybody help, how to sort in key-different ordering?

Petr Přikryl
  • 1,641
  • 4
  • 22
  • 34

1 Answers1

17

if you have numbers as values, you can use this:

stats.sort(key=lambda x: (-x['K'], -x['B'], x['A'], x['Z']))

For general values:

stats.sort(key=lambda x: (x['A'], x['Z']))
stats.sort(key=lambda x: (x['K'], x['B']), reverse=True) 
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197