
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to sort a nested Python dictionary?
If you have a dictionary of the following format:
{ 'KEY1':{'name':'foo','data':1351,'completed':100}, 'KEY2':{'name':'bar','data':1541,'completed':12}, 'KEY3':{'name':'baz','data':58413,'completed':18} }
And you want to sort by the key, completed within each entry, in a ascending order, you can use the sorted function with a lambda that specifies which key to use to sort the data. For example,
my_collection = { 'KEY1':{'name':'foo','data':1351,'completed':100}, 'KEY2':{'name':'bar','data':1541,'completed':12}, 'KEY3':{'name':'baz','data':58413,'completed':18} } sorted_keys = sorted(my_collection, key=lambda x: (my_collection[x]['completed'])) print(sorted_keys)
This will give the output:
['KEY2', 'KEY3', 'KEY1']
- Related Articles
- How to create nested Python dictionary?
- How to recursively iterate a nested Python dictionary?
- How to sort a dictionary in Python?
- How to count elements in a nested Python dictionary?
- How to sort a Python dictionary by datatype?
- How to sort a Python dictionary by value?
- Python Convert nested dictionary into flattened dictionary?
- Python - Convert flattened dictionary into nested dictionary
- How to sort a dictionary in Python by keys?
- How to sort a dictionary in Python by values?
- How to access nested Python dictionary items via a list of keys?
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- Convert Nested Tuple to Custom Key Dictionary in Python
- Python - Convert list of nested dictionary into Pandas Dataframe
- How to define a Python dictionary within dictionary?

Advertisements