How to Sort a Dictionary by Value in Python

Share This Post

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

spot_img

Related Posts

5 Reasons That Make MacBooks Good for Coding

Looking for a reliable laptop or computer for coding?...

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...
- Advertisement -spot_img