How do you sort a Python dictionary based on the inner value of a nested dictionary?
For example, sort mydict
below based on the value of context
:
mydict = { 'age': {'context': 2}, 'address': {'context': 4}, 'name': {'context': 1} }
The result should be like this:
{ 'name': {'context': 1}, 'age': {'context': 2}, 'address': {'context': 4} }
Method #1 : Using OrderedDict() + sorted() This task can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed.
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.
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
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.
>>> from collections import OrderedDict >>> mydict = { 'age': {'context': 2}, 'address': {'context': 4}, 'name': {'context': 1} } >>> OrderedDict(sorted(mydict.iteritems(), key=lambda x: x[1]['context'])) OrderedDict([('name', {'context': 1}), ('age', {'context': 2}), ('address', {'context': 4})])
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