Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: sort this dictionary (dict in dict)

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.

like image 577
user469652 Avatar asked Dec 02 '10 05:12

user469652


People also ask

How do you sort a dictionary in a dictionary Python?

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.

How do you sort dictionaries by dictionary value?

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.

Can you sort dictionary values in Python?

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.


1 Answers

dicts 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.

like image 112
unutbu Avatar answered Sep 28 '22 09:09

unutbu