Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of dictionaries by multiple keys with different ordering

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?

like image 721
Petr Přikryl Avatar asked Sep 12 '13 10:09

Petr Přikryl


People also ask

How do you sort a list in multiple dictionaries in Python?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function. See the following article for more information.

How do I sort a list of dictionaries in Python 3?

Use a lambda function as key function to sort the list of dictionaries. Use the itemgetter function as key function to sort the list of dictionaries.

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort multiple keys in Python?

To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by. Just pass the keys you want to sort by as a tuple for your sorting lambda expression.


1 Answers

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) 
like image 164
Roman Pekar Avatar answered Nov 15 '22 14:11

Roman Pekar