d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort by k'} }
Want to sort this dictionary by k as descending order, in python.
Little tricky, please help.
First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.
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.
We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
dict
s are unordered. So there is no way to sort them directly, but if you are
willing to convert the dict
into a list of (key,value)-tuples, then you could do this:
In [9]: d
Out[9]: {'a': {'b': 'whatever', 'k': 1}, 'b': {'b': 'sort by k', 'k': 2}}
In [15]: sorted(d.items(),key=lambda x: x[1]['k'],reverse=True)
Out[15]: [('b', {'b': 'sort by k', 'k': 2}), ('a', {'b': 'whatever', 'k': 1})]
This excellent mini-howto explains the use of the key
parameter.
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