Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Sort Python Dictionary by Key or Value - Python
Next article icon

Sort Python Dictionary by Key or Value - Python

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.

Sorting Dictionary By Key Using sort()

In this example, we will sort the dictionary by keys and the result type will be a dictionary. 

Python
d = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15}  myKeys = list(d.keys()) myKeys.sort()  # Sorted Dictionary sd = {i: d[i] for i in myKeys} print(sd) 

Output
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15} 

Displaying the Keys in Sorted Order using sorted() on Keys

In this example, we are trying to sort the dictionary by keys and values in Python. Here, keys() returns an iterator over the dictionary’s keys.

Python
# Initializing key-value pairs d = {2: 56, 1: 2, 5: 12, 4: 24}  print("Dictionary", d)  # Sorting and printing dictionary keys for i in sorted(d.keys()):     print(i, end=" ") 

Output
Dictionary {2: 56, 1: 2, 5: 12, 4: 24} 1 2 4 5 

Sorting the dictionary by key using OrderedDict

In this example, we will sort in lexicographical order Taking the key's type as a string.

Python
# Creates a sorted dictionary (sorted by key) from collections import OrderedDict  d = {'ravi': '10', 'rajnish': '9', 'abc': '15'} d1 = OrderedDict(sorted(d.items())) print(d1) 

Output
OrderedDict([('abc', '15'), ('rajnish', '9'), ('ravi', '10')]) 

Sorting the Keys Alphabetically Using Sorted on Dictionary

When we use sorted on a dictionary, it sorts by keys by default.

Python
# Initializing key-value pairs d = {2: 56, 1: 2, 3: 323}  print("Dictionary", d)  # Sorting and printing key-value pairs by the key for i in sorted(d):     print((i, d[i]), end=" ") 

Output
Dictionary {2: 56, 1: 2, 3: 323} (1, 2) (2, 56) (3, 323) 

Sorting Alphabetically by Values using Sorted

In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order.

Python
# Initializing the key-value pairs d = {2: 56, 100: 2, 3: 323}  print("Dictionary", d)  # Sorting key-value pairs by value, and by key if values are the same sorted_items = sorted(d.items(), key=lambda kv: (kv[1], kv[0]))  print(sorted_items) 

Output
Dictionary {2: 56, 100: 2, 3: 323} [(100, 2), (2, 56), (3, 323)] 

Sorting Dictionary By Value using Numpy

In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values.

Python
# Creates a sorted dictionary (sorted by key) from collections import OrderedDict import numpy as np  d = {'ravi': 10, 'rajnish': 9,         'sanjeev': 15, 'yash': 2, 'suraj': 32} print(d)  keys = list(d.keys()) values = list(d.values()) sorted_value_index = np.argsort(values) sorted_dict = {keys[i]: values[i] for i in sorted_value_index}  print(sorted_dict) 

Output
{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32} {'yash': 2, 'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32} 


Sorting Dictionary By Value using sorted() method

In the below given example, the dictionary is sorted using a 'lambda' to obtain the desired result of sorting the dictionary based on values.

Python
# Key, Value of the dictionary defined d = {'watermelon': 1, 'apple': 2, 'banana': 3}          # Sort based on Values val_based = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])} # item[1] represents the sorting based on value  # Sort based on reverse of Values val_based_rev = {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}  # Print sorted dictionary print(val_based) print(val_based_rev) 

Output
{'watermelon': 1, 'apple': 2, 'banana': 3} {'banana': 3, 'apple': 2, 'watermelon': 1} 


Need for Sorting Dictionary in Python

We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Sorting is very important when we are dealing with a large amount of data. 

We can sort a dictionary by values using these methods:

  • First, sort the keys alphabetically using key_value.iterkeys() function.
  • Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
  • Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))

We have covered different examples based on sorting dictionary by key or value. Reading and practicing these Python codes will help you understand sorting in Python dictionaries.

You can easily sort the values of dictionaries by their key or value.

Similar Reads:

  • Sort a Dictionary
  • Different ways of sorting Dictionary by Values and Reverse
  • Different ways of sorting Dictionary by Keys and Reverse
  • Ways to sort list of dictionaries by values
  • Sort Dictionary key and values List

Next Article
Sort Python Dictionary by Key or Value - Python

T

Tanmay_Jain
Improve
Article Tags :
  • Misc
  • Python
  • python-dict
  • Python dictionary-programs
  • python
Practice Tags :
  • Misc
  • python
  • python
  • python-dict

Similar Reads

    Ways to sort list of dictionaries by values in Python – Using itemgetter
    In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently ut
    2 min read
    Python | Pandas Index.sort_values()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.sort_values() function is used to sort the index values. The function ret
    2 min read
    Python | Sort the list alphabetically in a dictionary
    In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is
    3 min read
    Python | Sort Tuples in Increasing Order by any key
    Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : So
    3 min read
    Python - Keys associated with value list in dictionary
    Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences