
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Sort a Dictionary by Its Values
								Certification: Intermediate Level
								Accuracy: 41.67%
								Submissions: 12
								Points: 5
							
							Write a Python program that sorts a dictionary by its values in ascending order.
Example 1
- Input: {'a': 3, 'b': 1, 'c': 2}
- Output: {'b': 1, 'c': 2, 'a': 3}
- Explanation: 
    - Step 1: Take the input dictionary {'a': 3, 'b': 1, 'c': 2}.
- Step 2: Extract the key-value pairs: [('a', 3), ('b', 1), ('c', 2)].
- Step 3: Sort the pairs by their values: [('b', 1), ('c', 2), ('a', 3)].
- Step 4: Reconstruct the dictionary from the sorted pairs.
- Step 5: Return the sorted dictionary {'b': 1, 'c': 2, 'a': 3}.
 
Example 2
- Input: {'x': 5, 'y': 2, 'z': 8}
- Output: {'y': 2, 'x': 5, 'z': 8}
- Explanation: 
    - Step 1: Take the input dictionary {'x': 5, 'y': 2, 'z': 8}.
- Step 2: Extract the key-value pairs: [('x', 5), ('y', 2), ('z', 8)].
- Step 3: Sort the pairs by their values: [('y', 2), ('x', 5), ('z', 8)].
- Step 4: Reconstruct the dictionary from the sorted pairs.
- Step 5: Return the sorted dictionary {'y': 2, 'x': 5, 'z': 8}.
 
Constraints
- 1 ≤ len(d) ≤ 10^3
- -10^5 ≤ d[key] ≤ 10^5
- Time Complexity: O(n log n), where n is the number of key-value pairs
- Space Complexity: O(n)
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use the sorted() function with key=lambda to sort by values.
- Convert the sorted result to a dictionary using dict().
- Use items() to get key-value pairs from the dictionary.
- Sort based on the second element of each tuple (the value) using key=lambda x: x[1].
- Ensure the output maintains the original key-value pairs in sorted order.
