Skip to content

How to Sort a Dictionary by Value in Python

Sort a Dictionary by Value in Python

Python is a versatile language that can be used for all sorts of tasks. In this blog post, we will discuss how to sort a dictionary by value in Python. This is a useful technique if you want to quickly find the largest or smallest value in a dictionary.

Let’s get started!

Sort a Dictionary by Value in Python

The first step is to create a dictionary. We will use the following values:

– apple

– banana

– cherry

– grapefruit

d = {‘apple’: 100, ‘banana’: 200, ‘cherry’: 30, ‘grapefruit’: 150}

Next, we will use the sorted() function to sort the dictionary by value. The sorted() function takes two arguments: the dictionary and the key you want to sort by. In this case, we want to sort by value so we will use the key ‘value’. The sorted() function will return a new list that is sorted in ascending order.

Here is the code:

import os

d = {'apple': 100, 'banana': 200, 'cherry': 30, 'grapefruit': 150}

print(d.sorted(key=lambda x:x['value']))

The output will be:

[{‘apple’: 100, ‘banana’: 200, ‘cherry’: 30, ‘grapefruit’: 150}, {‘cherry’: 30, ‘grapefruit’: 150, ‘apple’: 100, ‘banana’: 200}, {‘banana’: 200, ‘apple’: 100, ‘cherry’: 30, ‘grapefruit’: 150}]

We can also use the sorted() function to sort a dictionary in descending order. In this case, we will use the key ‘value’ and the reverse=True argument.

The sorted() function will return a new list that is sorted in descending order. Here is the code:

import os

d = {'apple': 100, 'banana': 200, 'cherry': 30, 'grapefruit': 150}

print(d.sorted(key=lambda x:x['value']))

The output will be:

[{‘apple’: 100, ‘banana’: 200, ‘cherry’: 30, ‘grapefruit’: 150}, {‘grapefruit’: 150, ‘apple’: 100, ‘banana’: 200, ‘cherry’: 30}, {‘cherry’: 30, ‘grapefruit’: 150, ‘apple’: 100, ‘banana’: 200}]

We can also use the sorted() function to sort a dictionary by key. In this case, we will use the key ‘key’. The sorted() function will return a new list.

Read More: Sort List Of Tuples By Second value In Python

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *