TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Sort Dictionary by Value With Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python Sort Dictionary by Value With Examples

Last updated: Apr 16, 2024 1:41 pm
By Soumya Agarwal
Share
7 Min Read
Python Sort Dictionary by Value With Examples
SHARE

Sorting a dictionary by its values is a common task in Python programming. In this tutorial, we will explore multiple methods to achieve this and provide you with a solid understanding. By the end of this tutorial, you’ll be equipped with various techniques that you can leverage in your programming projects.

Contents
Sort Dictionary Using Lambda FunctionSort Dictionary Using ItemGetter()Use Sorted() with Custom FunctionSort Dictionary Using OrderedDictSort Using List ComprehensionSort Using Pandas DataFrameFrequently Asked QuestionsQ1: Can I sort a dictionary in descending order using these methods?Q2: Is there a way to sort a dictionary in place?Q3: Can I sort a dictionary with different data types?Q4: How do I sort a dictionary by keys instead of values?

6 Ways to Sort Dictionary by Value in Python

Before we begin, let’s quickly review what a dictionary is in Python. A dictionary is an unordered collection of items, where each item consists of a key-value pair. Keys are unique, immutable, and used to access values associated with them. Here’s a quick example:

# Sample Dict
di_ct = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}

In the above dictionary, ‘apple’, ‘banana’, ‘orange’, and ‘kiwi’ are keys, and 5, 2, 8, and 3 are their respective values.

Must Read:
1. Python Dictionary to JSON
2. Python Append to Dictionary
3. Python Merge Dictionaries
4. Python Iterate Through a Dictionary
5. Python Search Keys by Value in a Dictionary
6. Python Multiple Ways to Loop Through a Dictionary
7. Python Insert a Key-Value Pair to the Dictionary

In Python, the sorting of arrays is achievable in many ways. Here, we’ll provide five such techniques to do this job. Firstly, check the sorted() method, one of Python’s built-in functions.

Sort Dictionary Using Lambda Function

The sorted() function is a versatile tool for sorting iterable objects in Python. By default, it sorts dictionaries based on keys. However, we can utilize the key parameter to specify sorting based on values. Here’s an example:

# Sort dict by values using sorted() and lambda function
new_dict = dict(sorted(di_ct.items(), key=lambda item: item[1]))

# Print the sorted dict
print(new_dict)

In this example, the key=lambda item: item[1] lambda function extracts the values for sorting, resulting in a dictionary sorted by its values in ascending order.

Sort Dictionary Using ItemGetter()

The operator module in Python provides a convenient itemgetter() function for extracting values or elements from an iterable. This can be particularly useful when sorting dictionaries. Here’s an example:

from operator import itemgetter

# Sort dict by values using itemgetter()
new_dict = dict(sorted(di_ct.items(), key=itemgetter(1)))

# Print the sorted dict
print(new_dict)

Here, itemgetter(1) is equivalent to the lambda function in the previous example, extracting values for sorting.

Use Sorted() with Custom Function

You can define a custom function to specify the sorting criteria for the dictionary. This offers flexibility for more complex sorting logic. Here’s an example.

# Custom func
def custom_sort(item):
    return item[1]

# Sort dict by values using custom func
sorted_dict_val_custom = dict(sorted(di_ct.items(), key=custom_sort, reverse=True))

# Print the sorted dict
print(sorted_dict_val_custom)

In this example, the custom_sort function returns the values, and the reverse=True parameter sorts in descending order.

Sort Dictionary Using OrderedDict

The collections module in Python provides the OrderedDict class, which maintains the order of the keys. We will leverage this feature in the below example:

from collections import OrderedDict

# Sort dict by values using OrderedDict
sorted_dict_val_ord = OrderedDict(sorted(di_ct.items(), key=lambda item: item[1]))

# Print the sorted dict
print(sorted_dict_val_ord)

The OrderedDict maintains the order of insertion, effectively resulting in a dictionary sorted by values.

Sort Using List Comprehension

You can use list comprehension to create a list of tuples and sort them using the sorted() function. Convert them back to a dictionary. Here’s an example.

# Sort dict by values using list comprehension and sorted()
sorted_dict_val_by_lc = dict(sorted([(k, v) for k, v in di_ct.items()], key=lambda item: item[1]))

# Print the sorted dict
print(sorted_dict_val_by_lc)

In this example, the list comprehension creates a list of tuples and sorted() sorts them based on values. The resulting list is then converted back into a dictionary.

Sort Using Pandas DataFrame

We can even use Pandas data frame to sort the dictionary by values. Try this if you have a large amount of data and processing of this size could impact the performance. Here’s an example of how you can get the sorting done using Pandas:

import pandas as pds

# Create a Data Frame from the dict
dfr = pds.DataFrame(list(di_ct.items()), columns=['Fruit', 'Quantity'])

# Sort Data Frame by values
sorted_df = dfr.sort_values(by='Quantity').set_index('Fruit').to_dict()['Quantity']

# Print the sorted dict
print(sorted_df)

In this example, the pandas library is used to create a data frame, which is then sorted by values, and the result is converted back into a dictionary.

Must Read: Pandas Series and DataFrame Explained in Python

Frequently Asked Questions

Go through the below FAQs addressing a few of the common concerns.

Q1: Can I sort a dictionary in descending order using these methods?

Answer: Yes! For methods using the sorted() function, you can achieve descending order by specifying the reverse parameter. For example:

# Sorting dictionary in descending order using sorted() and lambda function
sorted_dict_values_desc = dict(sorted(di_ct.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict_values_desc)

Q2: Is there a way to sort a dictionary in place?

Answer: The methods using sorted() do not modify the original object. If you want to sort it in place, you can use the collections.OrderedDict method:

# Sorting dictionary in-place using OrderedDict
di_ct = OrderedDict(sorted(di_ct.items(), key=lambda item: item[1]))
print(my_dict)

Q3: Can I sort a dictionary with different data types?

Answer: Yes, the methods mentioned in the tutorial apply to dictionaries with any comparable data types. Python’s sorting functions can handle a variety of data types, making them versatile for different scenarios.

Q4: How do I sort a dictionary by keys instead of values?

Answer: By default, dictionaries are sorted by keys. If you want to explicitly sort by keys, you can use the sorted() function without specifying the key parameter:

# Sorting dictionary by keys
sorted_dict_keys = dict(sorted(di_ct.items()))
print(sorted_dict_keys)

Feel free to experiment with these methods and adapt them to your specific use cases.

Sorting dictionaries is a common operation. Having multiple methods at your disposal ensures you can choose the most suitable approach for your use case.

Happy Coding,
Team TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Soumya Agarwal Avatar
By Soumya Agarwal
Follow:
I'm a BTech graduate from IIITM Gwalior. I have been actively working with large MNCs like ZS and Amazon. My development skills include Android and Python programming, while I keep learning new technologies like data science, AI, and LLMs. I have authored many articles and published them online. I frequently write on Python programming, Android, and popular tech topics. I wish my tutorials are new and useful for you.
Previous Article Python Sort List of Numbers or Integers Python Sort List of Numbers or Integers
Next Article 9 Ways to Python Sort Lists Alphabetically How to Sort Python Lists Alphabetically

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x