• Latest
  • Trending
How to sort dictionary by value in Python?

How to sort dictionary by value in Python?

April 26, 2022
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
Instagram fined €405m over children’s data privacy

Instagram fined €405m over children’s data privacy

September 6, 2022
8 Most Common Causes of a Data Breach

5.7bn data entries found exposed on Chinese VPN

August 18, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Saturday, 24 May, 2025
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

How to sort dictionary by value in Python?

by ITECHNEWS
April 26, 2022
in Data Science, Leading Stories
0 0
0
How to sort dictionary by value in Python?

In this tutorial, we look at various methods to sort the dictionary by value in Python. We will understand why it is required and how to do so.

Table of Contents – Python sort dictionary by value

  • Why do we need to sort the Python dictionary?
  • Various methods to sort dictionary by value in Python
  • By converting data in the dictionary to list
  • Using Bubble Sort
  • Using sorted() Method
  • Using itemgetter() Method
  • Using dict.items() and sorted() Functions
  • By performing operations directly on the dictionary
  • Using for Loop
  • Using the sorted() Function
  • Using a Lambda Function
  • Using dictionary.items() Method
  • Closing thoughts

Why do we need to sort the Python dictionary by value?

In Python, the dictionary stores unordered data that contains “key:value” pairs seperated by commas inside curly brackets. The Python dictionary class does not allow to sort to sort the items in its object. We can retrieve the values when the key exists and is known.

YOU MAY ALSO LIKE

ATC Ghana supports Girls-In-ICT Program

Vice President Dr. Bawumia inaugurates ICT Hub

Consider a huge amount of data in a Python dictionary. In this case, to reduce the complexity of data collection by sorting the data will lead to a quick output. Thus, to save time and increase efficiency over large data, like a phonebook, we need to sort the Python dictionary.

 

We can sort the dictionary using list and performing sorting over the list. Let us see the various ways to do this.

 

Various methods to sort dictionary by value in Python

By converting data in the dictionary to list

We will first look at way to convert the data in dictionary to a list. We then perform sorting over the list to sort the Python dictionary.

Example-

markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=list(markdict.items())
print(marklist)

Output-

[('Tom', 67), ('Tina', 54), ('Akbar', 87), ('Kane', 43), ('Divya', 73)]

 

Here, we are converting the dictionary to a list using the list() function. Once the list is ready, we can perform operations over it to get desired results on the dictionary.

Using Bubble Sort

Example –

markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
l=len(marklist)
  for i in range(l-1):
    for j in range(i+1,l):
      if marklist[i][1]>marklist[j][1]:
            t=marklist[i]
            marklist[i]=marklist[j]
            marklist[j]=t
    sortdict=dict(marklist)print(sortdict)

Output-

{'Kane': 43, 'Tina': 54, 'Tom': 67, 'Divya': 73, 'Akbar': 87}

 

In this example, we use simple Bubble sort using a temporary variable t and sorting the values in the list.

Using sorted() Method

The sorted() function in Python returns a sorted list from the specified iterables and returns a list of sorted items.

Syntax-

sorted (iterable, key, reverse)

Example-

marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

 

Here, in the sorted() function, the iterable is markdict.items and the key is set as lambda x:x[1]. After sorting the items, we create a new dictionary sortdict to call the sorted data.

Using itemgetter() Method

In Python, the itemgetter() function returns a callable object from its operand. Using the itemgetter() function with the sorted() function will return sorted items in the dictionary by value.

Example-

import operator

markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist= sorted(markdict.items(), key=operator.itemgetter(1)) 
sortdict=dict(marklist)
print(sortdict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

 

The operator.itemgetter(item) function returns a callable object that fetches item from its operand using the operand’s __getitem() method.

Using dict.items() and sorted() Functions

The dict.items() method and the sorted() function can be used together to return the list of items sorted by values in a dictionary.

Example-

markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=sorted((value, key) for (key,value) in markdict.items())
sortdict=dict([(k,v) for v,k in marklist])
print(sortdict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

In the above example, we sort the dictionary using sorted() function and create a new dictionary sortdict with the sorted values.

 

By performing operations directly on the dictionary

 

The Python dictionary can also be sorted without converting the items to list. Here are the ways to do it.

Using for Loop

By using a for loop along with sorted() function in Python, we can sort the dictionary by value. Here is an example for the same.

Example-

dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
sorted_values = sorted(dict1.values()) # Sort the values 
sorted_dict = {}  

for i in sorted_values:     
    for k in dict1.keys():         
        if dict1[k] == i:             
            sorted_dict[k] = dict1[k]             
            break
print(sorted_dict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

 

Here, we first use the sort() function to order the values of dictionary. The sorted() function does not re-order the dictionary in-place, hence, we store it’s value in sorted_values. We then then loop through the sorted values, finding the keys for each value. This is finally added to the new dictionary sorted_dict[k].

Using the sorted() Function

Example-

dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
sorted_dict = {} 
sorted_keys = sorted(dict1, key=dict1.get) 
for w in sorted_keys:     
  sorted_dict[w] = dict1[w]  
print(sorted_dict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

 

In this example, we use the function key on each element before comparing the values for sorting. Another function used here is get() to return the values corresponding to the dictionary’s key. Thus, the function sorted(dict1, key=dict1.get) returns the list of keys with sorted values.

Using a Lambda Function

We can use Python function sorted() with lambda function to sort a dictionary by value. The syntax of lambda function is as follows.

Syntax-

lambda arguments: expression

Example-

dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
sorted_tuples = sorted(dict1.items(), key=lambda item: item[1]) 
sorted_dict = {k: v for k, v in sorted_tuples}  
print(sorted_dict)

Output-

 

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

Using dictionary.items() Method

The items() method can sort the dictionary by values and return the sorted values. Below is the example of how we can use this method.

Example-

from operator import itemgetter
dictionary = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1))) 
print(sort_dict)

Output-

{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

 

In this example, we use the functions sorted(), set the iterable as dictionary.items() and the key as key=itemgetter(1) to get the sorted values of the dictionary.

Closing thoughts

We can sort the Python dictionary by values in two ways. One is by converting dictionary data to list and then sorting the list. The other way is to sort the dictionary directly.

Source: hrishikesh1990
Via: dev.to
Tags: How to sort dictionary by value in Python?
ShareTweetShare
Plugin Install : Subscribe Push Notification need OneSignal plugin to be installed.

Search

No Result
View All Result

Recent News

ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023

Recent News

  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Co-Creation Hub’s edtech accelerator puts $15M towards African startups February 20, 2023
  • Data Leak Hits Thousands of NHS Workers February 20, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© 2021-2022 iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Go to mobile version