Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Python dictionary based on nested dictionary values

Tags:

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}        } 
like image 661
Regal Paris Avatar asked Aug 01 '12 06:08

Regal Paris


People also ask

How do you sort nested dictionary by value in Python?

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.

How do you sort a list of dictionaries based on values 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.

How do you sort dictionaries in Python dictionary?

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.

Can we do sorting in dictionary 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

>>> 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})]) 
like image 182
jamylak Avatar answered Apr 05 '23 22:04

jamylak