 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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. 
Advertisements
 