Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Sort Dictionaries by Size
When working with Python dictionaries, you often need to sort them by their size (number of key-value pairs). Python provides several approaches to accomplish this using the len() function as a sorting key.
Using a Custom Function with sort()
The most straightforward approach is to define a helper function that returns the length of each dictionary ?
def get_len(element):
return len(element)
dict_list = [
{24: 56, 29: 11, 10: 22, 42: 28},
{54: 73, 59: 11},
{13: 39},
{31: 22, 59: 73, 57: 44}
]
print("Original dictionary list:")
print(dict_list)
dict_list.sort(key=get_len)
print("\nSorted by size (ascending):")
print(dict_list)
Original dictionary list:
[{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}]
Sorted by size (ascending):
[{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]
Using Lambda Function
You can achieve the same result more concisely using a lambda function ?
dict_list = [
{24: 56, 29: 11, 10: 22, 42: 28},
{54: 73, 59: 11},
{13: 39},
{31: 22, 59: 73, 57: 44}
]
# Sort in ascending order
dict_list.sort(key=lambda x: len(x))
print("Ascending order:")
print(dict_list)
# Sort in descending order
dict_list.sort(key=lambda x: len(x), reverse=True)
print("\nDescending order:")
print(dict_list)
Ascending order:
[{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]
Descending order:
[{24: 56, 29: 11, 10: 22, 42: 28}, {31: 22, 59: 73, 57: 44}, {54: 73, 59: 11}, {13: 39}]
Using sorted() Function
The sorted() function creates a new sorted list without modifying the original ?
dict_list = [
{24: 56, 29: 11, 10: 22, 42: 28},
{54: 73, 59: 11},
{13: 39},
{31: 22, 59: 73, 57: 44}
]
# Original list remains unchanged
sorted_list = sorted(dict_list, key=len)
print("Original list:")
print(dict_list)
print("\nNew sorted list:")
print(sorted_list)
Original list:
[{24: 56, 29: 11, 10: 22, 42: 28}, {54: 73, 59: 11}, {13: 39}, {31: 22, 59: 73, 57: 44}]
New sorted list:
[{13: 39}, {54: 73, 59: 11}, {31: 22, 59: 73, 57: 44}, {24: 56, 29: 11, 10: 22, 42: 28}]
Comparison
| Method | Modifies Original | Best For |
|---|---|---|
list.sort() |
Yes | In-place sorting |
sorted() |
No | Creating new sorted list |
| Lambda function | Depends on method used | Concise one-liners |
Conclusion
Use list.sort(key=len) for in-place sorting or sorted(list, key=len) to create a new sorted list. Both methods efficiently sort dictionaries by their size using the len() function.
Advertisements
