I need sort this list of dictionaries:
[ {K: 1, B: 2, A: 3, Z: 4, ... } , ... ]
Ordering should be:
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?
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.
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.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With