How to Sort a Dictionary by Value in Python

In this tutorial, we’ll learn how to program "How to Sort a Dictionary by Value in Python." The objective is to safely and efficiently sort a dictionary based on its values. This tutorial will guide you through the process step by step, ensuring a clear understanding of how to implement the sorting effectively. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the proper way to sort a dictionary based on its values. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. member_age = {
  2.     'Claire': 23,
  3.     'John': 21,
  4.     'Cyrus': 25,
  5.     'Denver': 26
  6. }
  7.  
  8.  
  9. while True:
  10.     print("\n================= Sort a Dictionary by Value =================\n\n")
  11.  
  12.     print("Current Value: ", member_age)
  13.     print("\n")
  14.     key=int(input("Enter a key value: "))
  15.  
  16.     sort_value = dict(sorted(member_age.items(), key=lambda item: item[key-1]))
  17.     print("\n", sort_value)
  18.  
  19.  
  20.     opt = input("\nDo you want to try again?(yes/no): ")
  21.  
  22.     if opt.lower() == 'yes':
  23.         ret=False
  24.     elif opt.lower() == 'no':
  25.         ret=True
  26.         print("Exiting program....")
  27.     else:
  28.         print("Please enter yes/no:")
  29.         break
  30.  
  31.     if ret == False:
  32.         continue

The program sorts a dictionary by its values in ascending order, displays the original dictionary and the sorted result, and allows the user to repeat the process or exit the program based on their input.

Output:

There you have it we successfully created How to Sort a Dictionary by Value in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment