Python

How to sort a Dictionary by value in Python

Hello in this tutorial, we will see how to sort a dictionary by value in python programming.

1. Introduction

To perform sorting a dictionary by the value we will use the sorted(….) function. The function returns a sorted list of the specified object.sort dictionary by value python

Method syntax

sorted(iterable, key=key, reverse=reverse)

Where:

  • iterable attribute represents a sequence for sorting the list, dictionary, etc
  • key attribute represents an optional field that serves as the key for the sort comparison
  • reverse attribute represents an optional boolean to determine the sorting order. Default is false (meaning ascending order)

1.2 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. How to sort a Dictionary by value in Python

I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating an implementation file

Add the following code to the python script. The script contains a dictionary object which will be sorted by value with the help of sorted(…) function in python.

jcg-assignment-sort-dict-by-value.py

# how to sort the dictionary by value

from operator import itemgetter


# sorting dictionary using the sorted() function
def dictionairy():
    orders = {
        'tuna chunk light': 102.5,
        'salads': 54,
        'turkey': 56,
        'espresso': 72,
        'potato chips': 48,
        'cheese': 41,
    }

    # the sorted function will sort the dictionary by values of each entry within
    # the dictionary from smallest to largest
    sorted_orders = sorted(orders.items(), key=lambda item: item[1])

    # to sort it in descending order just add reverse=True
    # sorted_orders = sorted(orders.items(), key=lambda item: item[1], reverse=True)

    print('Sorting the items by values')
    print(sorted_orders)


# using operator module
def dictionairybyitemgetter():
    orders = [
        {'item': 'tuna chunk light', 'price': 102.5},
        {'item': 'salads', 'price': 54},
        {'item': 'turkey', 'price': 56},
        {'item': 'espresso', 'price': 72},
        {'item': 'potato chips', 'price': 48},
        {'item': 'cheese', 'price': 41}
    ]

    sorted_orders = sorted(orders, key=itemgetter('price'))

    # to sort it in descending order just add reverse=True
    # sorted_orders = sorted(orders, key=itemgetter('price'), reverse=True)

    print('Sorting the items by price')
    print(sorted_orders)


def main():
    # function calling
    dictionairy()
    print('\n')
    dictionairybyitemgetter()


# driver code
if __name__ == '__main__':
    main()

print('\ndone')

Run this python script and if everything goes well the output will be shown in the IDE console describing that the dictionary object will be sorted by values.

Console output

Sorting the items by values
Sorting the items by values
[('cheese', 41), ('potato chips', 48), ('salads', 54), ('turkey', 56), ('espresso', 72), ('tuna chunk light', 102.5)]


Sorting the items by price
[{'item': 'cheese', 'price': 41}, {'item': 'potato chips', 'price': 48}, {'item': 'salads', 'price': 54}, {'item': 'turkey', 'price': 56}, {'item': 'espresso', 'price': 72}, {'item': 'tuna chunk light', 'price': 102.5}]

done

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned about the sorted(…) function that sorts a dictionary object by values. The function takes 1 mandatory and 2 optional attributes which can be played around to better understand the implementation. You can download the source code of this tutorial from the Downloads section.

4. Download the Project

Download
You can download the full source code of this example here: How to sort a Dictionary by value in Python

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button