Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/How do you sort a dictionary based on values?

How do you sort a dictionary based on values?

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To sort a dictionary by its values, you first extract its key value pairs as an iterable of tuples, then sort this iterable, and finally, if desired, reconstruct a new dictionary from the sorted…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
HCL

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like HCL. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
338 wordsIncludes code

To sort a dictionary by its values, you first extract its key-value pairs as an iterable of tuples, then sort this iterable, and finally, if desired, reconstruct a new dictionary from the sorted pairs. The most common Pythonic approach involves using the sorted() function with a custom key.

Mechanics and Why

Python dictionaries are inherently unordered before version 3.7, and even after, they maintain insertion order, not value-based sorted order. To sort by values, you must convert the dictionary's items into a sortable sequence. d.items() returns a view of key-value pairs as tuples (e.g., ('a', 10)). The sorted() function then takes this iterable and sorts it. The key=lambda x: x[1] argument specifies that the sorting should be based on the second element of each tuple (the value). Alternatively, operator.itemgetter(1) can be used for slightly better performance and readability in some contexts. To sort in descending order, add reverse=True.

The output of sorted() is always a list of tuples. If you need a dictionary where the insertion order reflects this sort, you can pass this list back to the dict() constructor.

data = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_items = sorted(data.items(), key=lambda item: item[1])
# sorted_items will be [('banana', 1), ('cherry', 2), ('apple', 3)]

# To get a new dictionary with insertion order reflecting the sort:
sorted_dict = dict(sorted_items)
# sorted_dict will be {'banana': 1, 'cherry': 2, 'apple': 3}

Production Considerations and Cost

This operation has a time complexity of O(n log n) due to the sorting algorithm. For large dictionaries, this approach loads all items into memory, which can be a bottleneck. In data engineering contexts, sorting large datasets often involves distributed processing frameworks like Apache Spark. Spark's sortByKey or orderBy operations, for instance, trigger a "shuffle" phase, which redistributes data across partitions to ensure global ordering, a much more resource-intensive process than in-memory Python sorting.

In the interview, also mention that the output is fundamentally a list of tuples representing the sorted order, as dictionaries themselves don't maintain a value-based sorted state.

⚡
Pro Tip

Pro-Move: itemgetter. Red Flag: Sorting keys only.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer