Given a Dictionary List, perform sort by size of dictionary.
Input : test_list = [{4:6, 9:1, 10:2, 2:8}, {4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}]
Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]
Explanation : 1 < 2 < 3 < 4, sorted by number of keys of dictionary.
Input : test_list = [{4:3, 9:1}, {3:9}, {1:2, 9:3, 7:4}]
Output : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}]
Explanation : 1 < 2 < 3, sorted by number of keys of dictionary.
OutputThe original list is : [{4: 6, 9: 1, 10: 2, 2: 8}, {4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
Sorted List : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]
Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”. len() + sort() performs n*nlogn number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
OutputThe original list is : [{4: 6, 9: 1, 10: 2, 2: 8}, {4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
Sorted List : [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]
The given problem statement asks to sort a list of dictionaries based on the size of each dictionary.
1. Define a function to get the length of the dictionary.
2. Use map() to apply the function to each dictionary in the original list.
3. Use zip() to combine the list of lengths with the original list of dictionaries.
4. Use sorted() to sort the list of tuples based on the length of each dictionary.
5. Extract the sorted list of dictionaries using a list comprehension.
OutputOriginal List: [{4: 6, 9: 1, 10: 2, 2: 8}, {4: 3, 9: 1}, {3: 9}, {1: 2, 9: 3, 7: 4}]
Sorted List: [{3: 9}, {4: 3, 9: 1}, {1: 2, 9: 3, 7: 4}, {4: 6, 9: 1, 10: 2, 2: 8}]