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.

Updated on: 08-Sep-2021

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements