Tutorialspoint
Problem
Solution
Submissions

Sort a Dictionary by Its Keys

Certification: Intermediate Level Accuracy: 0% Submissions: 2 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)
Functions / MethodsDictionaries Goldman SachsSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the sorted() function with key=lambda to sort by keys.
  • Convert the sorted result back into a dictionary using dict().
  • Use items() to get key-value pairs from the dictionary.

Steps to solve by this approach:

 Step 1: Get all (key, value) pairs from the dictionary using items().
 Step 2: Sort these pairs using the sorted() function.
 Step 3: Specify a key function lambda x: x[0] to sort by the first element (key).
 Step 4: Convert the sorted list of tuples back to a dictionary with dict().
 Step 5: This preserves the key-value associations while ordering by keys.
 Step 6: Return the new dictionary with sorted keys.
 Step 7: Example: {'c': 3, 'a': 1, 'b': 2} becomes {'a': 1, 'b': 2, 'c': 3}.

Submitted Code :