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.- member_age = {
- 'Claire': 23,
- 'John': 21,
- 'Cyrus': 25,
- 'Denver': 26
- }
- while True:
- print("\n================= Sort a Dictionary by Value =================\n\n")
- print("Current Value: ", member_age)
- print("\n")
- key=int(input("Enter a key value: "))
- sort_value = dict(sorted(member_age.items(), key=lambda item: item[key-1]))
- print("\n", sort_value)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- 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
Add new comment
- 16 views