Tutorialspoint
Problem
Solution
Submissions

Sort a Dictionary by Its Values

Certification: Intermediate Level Accuracy: 100% Submissions: 1 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)
ListDictionaries AccentureSnowflake
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 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.

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[1] to sort by the second element (value).
 Step 4: Convert the sorted list of tuples back to a dictionary with dict().
 Step 5: This creates a new dictionary ordered by values (ascending).
 Step 6: Return the new dictionary with keys ordered by their values.
 Step 7: Example: {'a': 3, 'b': 1, 'c': 2} becomes {'b': 1, 'c': 2, 'a': 3}.

Submitted Code :