- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Python Dictionaries by Key or Value
When it is required to sort the dictionaries in Python using a key or a value, a dictionary can be defined, and key value pairs can be inserted into it. A ‘for’ loop can be used to iterate through the key value pair, and sort it using ‘sort’ method. This method can be called.
Below is the demonstration of the same −
Example
def my_dict(): my_key_value_pair ={} my_key_value_pair[2] = 56 my_key_value_pair[1] = 2 my_key_value_pair[5] = 12 my_key_value_pair[4] = 24 my_key_value_pair[6] = 18 my_key_value_pair[3] = 323 print ("The keys and values after sorting in alphabetical order based on the key are : ") for i in sorted (my_key_value_pair) : print((i, my_key_value_pair[i])) my_dict()
Output
The keys and values after sorting in alphabetical order based on the key are : (1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Explanation
A method is defined, that initially assigns an empty dictionary to a variable.
The index of the empty dictionary is accessed and elements are assigned to indices.
The ‘sorted’ method is used to iterate through the dictionary, and display it on the console.
This method is called.
The output is displayed on the console.
- Related Articles
- Python – Sort Dictionaries by Size
- Python - Filter dictionaries by values in Kth Key in list
- Ways to sort list of dictionaries by values in Python
- Ways to sort list of dictionaries by values in Python Using itemgetter
- Sort list of dictionaries by values in C#
- How to sort a list of dictionaries by values of dictionaries in C#?
- Ways to sort list of dictionaries by values in Python Using lambda function
- How to Sort object of objects by its key value JavaScript
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Python – Dictionaries with Unique Value Lists
- JavaScript - Sort key value pair object based on value?
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Sort Tuples in Increasing Order by any key in Python program
- Python program to sort tuples in increasing order by any key.
- Ways to sort list of dictionaries using values in python

Advertisements