How to Sort a Dictionary by Key or Value in Python
In this tutorial, we’ll learn how to program “How to Sort a Dictionary by Key or Value in Python.” The objective is to safely sort a dictionary based on its keys or values. This tutorial will guide you through the process step by step to achieve an efficient sorting method. 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 illustrate the correct way to sort a dictionary by key or value. 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.- from collections import OrderedDict
- import numpy as np
- my_dict = {'John': 12, 'Claire': 7,
- 'Clark': 14, 'Stark': 5, 'Roger': 24}
- while True:
- print("\n================= Sort a Dictionary by Key or Value =================\n\n")
- print("Current Dictionary: ", my_dict)
- keys = list(my_dict.keys())
- values = list(my_dict.values())
- sorted_value_index = np.argsort(values)
- sorted_dict = {keys[i]: values[i] for i in sorted_value_index}
- print("New Dictionary: ", sorted_dict)
- 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
This program sorts a dictionary by its values in ascending order using NumPy and prints the new sorted dictionary while allowing the user to run it again if desired.
Output:

There you have it we successfully created How to Sort a Dictionary by Key or 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
- 37 views