Python List Advanced Exercise - Sort a list of dictionaries based on values of a key
14. Sort List of Dictionaries by Key Value
Write a Python function to sort a list of dictionaries based on values of a key.
Sample Solution:
Python Code:
Sample Output:
Original list: [[1, 4, 5], [1, 3, 4], [2, 6, 7, 8]] Merge k Sorted Lists into a list: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8] Original list: [[1, 2], [-1, -2, -3], [0]] Merge k Sorted Lists into a list: [-3, -2, -1, 0, 1, 2]
Flowchart:
What is the time complexity and space complexity of the following Python code?
Time complexity - The time complexity of the merge_k_sorted_lists() function is O(n log n), where n is the total number of elements across all the lists. Each element in each list is iterated over and pushed onto the heap, which takes O(log n) time, and then it is popped off the heap, which also takes O(log n) time.
Space complexity - The space complexity is O(n), because we store all the elements from the input lists on the heap. The heap will take up O(n) space, since it needs to store all the elements. Additionally, we create a list of lengths n to hold the output, but this is negligible compared to the size of the heap.
For more Practice: Solve these Related Problems:
- Write a Python function to sort a list of dictionaries in ascending order based on a specified key using sorted() with a lambda.
- Write a Python program to sort a list of dictionaries by a given key in descending order while handling missing keys with a default value.
- Write a Python function to implement multi-key sorting for a list of dictionaries using a custom comparator.
- Write a Python program to sort dictionaries by a key and then by another key if there is a tie, using tuple-based keys.
Go to:
Previous: Implement a LRU cache.
Next: List all pairs whose sum equals a given value.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.