
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Sort a Dictionary by Its Keys
								Certification: Intermediate Level
								Accuracy: 66.67%
								Submissions: 6
								Points: 5
							
							Write a Python program that sorts a dictionary by its keys in ascending order.
Example 1
- Input: {'c': 3, 'a': 1, 'b': 2}
- Output: {'a': 1, 'b': 2, 'c': 3}
- Explanation: 
    - Step 1: Take the input dictionary {'c': 3, 'a': 1, 'b': 2}.
- Step 2: Extract the key-value pairs: [('c', 3), ('a', 1), ('b', 2)].
- Step 3: Sort the pairs by their keys: [('a', 1), ('b', 2), ('c', 3)].
- Step 4: Reconstruct the dictionary from the sorted pairs.
- Step 5: Return the sorted dictionary {'a': 1, 'b': 2, 'c': 3}.
 
Example 2
- Input: {'z': 8, 'y': 2, 'x': 5}
- Output: {'x': 5, 'y': 2, 'z': 8}
- Explanation: 
    - Step 1: Take the input dictionary {'z': 8, 'y': 2, 'x': 5}.
- Step 2: Extract the key-value pairs: [('z', 8), ('y', 2), ('x', 5)].
- Step 3: Sort the pairs by their keys: [('x', 5), ('y', 2), ('z', 8)].
- Step 4: Reconstruct the dictionary from the sorted pairs.
- Step 5: Return the sorted dictionary {'x': 5, 'y': 2, '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 withkey=lambdato sort by keys.
- Convert the sorted result back into a dictionary using dict().
- Use items()to get key-value pairs from the dictionary.
