Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Python - Remove Dictionary Key Words
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
Python - Remove Dictionary Key Words

T

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

Similar Reads

  • Python | Set 4 (Dictionary, Keywords in Python)
    In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value ca
    5 min read
  • Get Key from Value in Dictionary - Python
    The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
    6 min read
  • Python - Remove Dictionary Key Words
    We are given a dictionary we need to remove the dictionary key words. For example we are given a dictionary d = {'a': 1, 'b': 2} we need to remove the dictionary key words so that the output becomes {'b': 2} . We can use method like del , pop and other methods to do it. Using del keyworddel keyword
    3 min read
  • 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 u
    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 | Pandas Dataframe.sort_values() | Set-2
    Prerequisite: Pandas DataFrame.sort_values() | Set-1 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 sort_values() function so
    3 min read
  • Filter Dictionary of Tuples by Condition - Python
    This task involves filtering the items of a dictionary based on a specific condition applied to the values, which are tuples in this case. We will check certain conditions for each tuple in the dictionary and select the key-value pairs that satisfy the condition. Given the dictionary a = {'a': (6, 3
    3 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    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
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