
- 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
Python – Sort Dictionaries by Size
When it is required to sort dictionaries by size, a method is defined that takes one parameter and uses ‘len’ to determine the output.
Below is a demonstration of the same −
Example
def get_len(element): return len(element) my_dict = [{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}] print("The dictionary is :") print(my_dict) my_dict.sort(key=get_len) print("The result is :") print(my_dict)
Output
The dictionary is : [{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}] The result is : [{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]
Explanation
A method named ‘get_len’ is defined that takes element as a parameter, and returns length of the element as output.
A list of dictionary is defined and displayed on the console.
The dictionary is sorted and the key is specified as the previously defined method.
This is the output that is displayed on the console.
- Related Articles
- Sort Python Dictionaries by Key or Value
- Ways to sort list of dictionaries by values in Python
- Ways to sort list of dictionaries by values in Python Using itemgetter
- Sort list of dictionaries by values in C#
- How to sort a list of dictionaries by values of dictionaries in C#?
- Python – Sort grouped Pandas dataframe by group size?
- Ways to sort list of dictionaries by values in Python Using lambda function
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Python – Descending Order Sort grouped Pandas dataframe by group size?
- Python – Ascending Order Sort grouped Pandas dataframe by group size?
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Ways to sort list of dictionaries using values in python
- Python - Filter dictionaries by values in Kth Key in list
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency

Advertisements