Python sort a dictionary by value

Sorted is a built-in function of python language which is used to store elements of a random sequence into a specific order. Sorting multiple values Separate by “comma” specifying the correct order in which to …

Python sort a dictionary by value

Sorted is a built-in function of python language which is used to store elements of a random sequence into a specific order. Sorting multiple values Separate by “comma” specifying the correct order in which to organize. 

First, we must know

What is a Dictionary in python?

A dictionary in any language is a collection of items that enhance the readability of programs. Python dictionary stores items as in key-value pairs. Different functions are used to store a dictionary by its value to put the element in a certain order. 

Dictionaries are mutable in which items can be added, deleted, or updated. Values are immutable and any data type that can be repeated in opposition to the key should be unique. Dictionary key-value pairs should be defined in curly braces with the right side of the colon is key and on the left side is value on which key is mapped.

There are multiple ways to sort Python dictionaries, we are targeting how to sort a dictionary by using various methods.

There are most common ways to sort a dictionary by its values.

  1. Python sort dictionary by values in ascending order (sorted () Method to sort a dictionary by values)
  2. Python sort dictionary by value alphabetically (Lambda along with sorted () Method) 
  3. Pythons sort a dictionary by value numerically 
  4. Python sort dictionary by value alphabetically (item.getter () along with sorted() Method)
  5. Sort a list of dictionaries by values python
  6. Python sort dictionary of dictionaries by a value
  7. Python sort dictionary by value descending and key ascending.

1. Python sort dictionary by values in ascending order

Method 1: sorted () Method

This method is a general sorting method that sorts a dictionary with the help of a loop in ascending order. This is the general syntax of sorting value that can be used in all types of sorting with different functions inside it.

Syntax

Sorted (iterable, key, reverse)

The above-mentioned method contains three parameters:

  • Iterable (mandatory):  It can be a tuple or a dictionary. 
  • Key (optional):  key argument used to sort comparisons. By default, the value is None.
  • Reverse(optional):  Boolean parameter which sorts dictionaries into ascending or descending order. If you select True value, the result will be in descending order of a sorted list.

Look at an example that defines sorting by simple sorted () function.

Code

  • Define dictionary
  • Use for loop with a sorted method to sort all values.
  • Use the get method that returns all values related to keys.
dict ={'d': 4, 'a': 1, 'e':5, 'c': 3, 'b':2}
for a in sorted (dict, key = dict.get):
 print(a,dict[a])

Output

a 1
b 2
c 3
d 4
e 5

By using the Reverse parameter as “True” value in the sorted () method, you can change a list or dictionary into reverse/descending order as mentioned below code.

Code

dict = {'d': 4, 'a': 1, 'e':5, 'c': 3, 'b':2}
for a in sorted (dict, key = dict.get, reverse=True):
 print(a,dict[a])

Output

e 5
d 4
c 3
b 2
a 1
In [ ]:

2. Python sort dictionary by value alphabetically

Method 2: Lambda along with sorted () Method

Lambda function is an anonymous function meaning this function does not need to be defined as other functions and used to perform small one-line expressions. It may take the number of arguments but does not run more than one-line expressions. It is a faster method to run small expressions. 

Syntax 

sorted (key= lambda arguments: expression)

Code

Use the code with “1” as the index number of  “item” if you want to sort a dictionary based on values.

dict={"Apple": 4,"Cherry":2,"Banana":6,"Guava":1,"GrapeFruit":5}
print({k:v for k,v in sorted (dict.items(), key=lambda item:item[0])})

Output

{'Apple': 4, 'Banana': 6, 'Cherry': 2, 'Grapefruit': 5, 'Guava': 1}

3. Pythons sort a dictionary by value numerically

Code

 Use “0” to sort a dictionary by key in python.

dict={"Apple": 4,"Cherry":2,"Banana":6,"Guava":1,"GrapeFruit":5}
print({k:v for k,v in sorted (dict.items(), key=lambda item:item[1])})

output

{'Guava': 1, 'Cherry': 2, 'Apple': 4, 'GrapeFruit': 5, 'Banana': 6}

4. Python sort dictionary by value alphabetically

Method 3: item.getter() along with sorted () Method

 item.getter is a built-in function of the operator module that builds a callable and accepts an iterable (tuple set or dictionary) as input at the nth position. The function uses the specific key to derive the value of the item.  

Syntax

operator.itemgetter(value)

import operator 
d = {'d': 7, 'a': 1, 'e':3, 'c': 3, 'b':2}
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('dictionary:',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0), reverse= True)
print('dictionary:',sorted_d)

Output

dictionary: [('a', 1), ('b', 2), ('c', 3), ('d', 7), ('e', 3)]
dictionary: [('e', 3), ('d', 7), ('c', 3), ('b', 2), ('a', 1)]

To access a particular value from the dictionary, you can use the item.getter function with the key name. Suppose in the below example, we want to access the value of key “d” of the dictionary that we mention with the item.getter function.

Code

from operator import itemgetter
dict = {'d': 4, 'a': 1, 'e':5, 'c': 3, 'b':2}
print(itemgetter('d')(dict))
#Output
#4

 “Ordedict” is a sorting function used in the older version (less than 3.0) of the python platform to sort the list.

5. Sort list of dictionaries by value Python

Sort a list of dictionaries in python with the help of their elements. Below is the coding example of sorting multiple dictionaries that are closed in list square brackets.

  • Define dictionaries inside the square brackets.
  • Sort list of dictionaries by lambda function according to “item”.
  • Sorting according to item value, dictionaries sort alphabetically.
  • Sorting according to color, item, and then price respectively.
  • All sorting alphabetically.
a = [{"item": "Shirt", "color": "blue","price":800},
{"item": "Shoes", "color": "black","price":900},
{"item": "Wristwatch", "color": "Brown","price":500},
{"item": "Perfume", "color": "pink", "price": 400},
{"item": "Tie", "color": "black", "price": 200}]
# Using sorted and lambda to print sorted list according to item
print ("This list is sorted according to items: ")
print (sorted (a, key = lambda i: i['item']))
print ("\n")
#Sort according to color, item, price
print ("This list is sorted according to item, their color and price: ")
print (sorted (a, key = lambda i: (i['color'], i['item'], i['price'])))
print ("\n")

Output

This list is sorted according to items: 
[{'item': 'Perfume', 'color': 'pink', 'price': 400}, {'item': 'Shirt', 'color': 'blue', 'price': 800}, {'item': 'Shoes', 'color': 'black', 'price': 900}, {'item': 'Tie', 'color': 'black', 'price': 200}, {'item': 'Wristwatch', 'color': 'Brown', 'price': 500}]


This list is sorted according to item, their color and price: 
[{'item': 'Wristwatch', 'color': 'Brown', 'price': 500}, {'item': 'Shoes', 'color': 'black', 'price': 900}, {'item': 'Tie', 'color': 'black', 'price': 200}, {'item': 'Shirt', 'color': 'blue', 'price': 800}, {'item': 'Perfume', 'color': 'pink', 'price': 400}]

This is the dictionary that is sorted by value numerically.

  • Define dictionaries inside the dictionary.
  • Use index number “1” for the item to sort the dictionaries according to values.
  • Use the key name “Average_marks” that values you want to sort along with lambda function inside a loop.
Result = {
            'class1' : {'subject':'DS', 'Average_marks':77},
            'class2' : {'subject':'Calculus', 'Average_marks':56},
            'class3' : {'subject':'OS', 'Average_marks':82},
            'class4' : {'subject':'MAPD', 'Average_marks':79},
            'class5' : {'subject':'OOP', 'Average_marks':72},
            }

for a in sorted(Result.items(), key=lambda k_v: k_v[1]['Average_marks']):
 print (a)

Output

('class2', {'subject': 'Calculus', 'Average_marks': 56})
('class5', {'subject': 'OOP', 'Average_marks': 72})
('class1', {'subject': 'DS', 'Average_marks': 77})
('class4', {'subject': 'MAPD', 'Average_marks': 79})
('class3', {'subject': 'OS', 'Average_marks': 82})

7. Python sort dictionary by value descending and key ascending

  • Define a dictionary. 
  • Sort dictionary with a simple lambda function.
  • x [1]: sort according to value first, then X [0]: sort according to key.
  • x [1] would be the values of the dictionary. It is negative so that bigger values come before the smaller ones (descending order)
d = {'banana': 3, 'orange': 5, 'apple': 5}
a=sorted(d.items(), key=lambda x: (-x[1], x[0]))
print(a)

Output

[('apple', 5), ('orange', 5), ('banana', 3)]

Conclusion

In this article, there are three common ways to sort a dictionary by its values instead of the key which helps to find the unique key by knowing its value. This article also covers the python sort the dictionary or dictionaries by value, python sort the list of dictionaries by value, Python sort dictionary by value descending and key ascending, numerically with simple programming examples.

Leave a Comment