TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Sort a Dictionary by Key With Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python Sort a Dictionary by Key With Examples

Last updated: Apr 14, 2024 11:35 am
By Soumya Agarwal
Share
8 Min Read
Python Sort a Dictionary by Key With Examples
SHARE

Welcome to this Python tutorial where we will explore different methods to sort a dictionary by its keys. Sorting dictionaries is a common task in programming, and Python provides multiple ways to achieve this. By the end of this tutorial, you’ll have a clear understanding of various approaches to sorting dictionaries and be able to choose the one that fits your specific needs.

Contents
Method 1: Using the sorted() functionMethod 2: Using items() method with sorted()Method 3: Using collections.OrderedDictMethod 4: Using the Lambda Function with sorted()Method 5: Using operator.itemgetter()FAQs: Sorting Python DictionariesQ1: Can I sort a dictionary in descending order?Q2: How to sort a dictionary based on values?Q3: Can a dict be sorted in place?Q4: How to sort a dict based on a custom criterion?Q5: Why choose OrderedDict over other methods?Q6: Can these methods handle dicts with different data types?Conclusion – Sort Dictionary By Key

Must Read:
1. Python Sorting a Dictionary
2. Python Dictionary to JSON
3. Python Append to Dictionary
4. Python Merge Dictionaries
5. Python Iterate Through a Dictionary
6. Python Search Keys by Value in a Dictionary
7. Python Multiple Ways to Loop Through a Dictionary
8. Python Insert a Key-Value Pair to the Dictionary

5 Ways to Sort Dictionary by Keys

Before we dive into sorting dictionaries, let’s make sure you have a basic understanding of Python dictionaries. If you’re not familiar with dictionaries, they are key-value pairs, and in Python, they are defined using curly braces {}. Here’s a quick refresher:

# Example Dictionary
my_dict = {'banana': 3, 'apple': 1, 'orange': 2}

In the above example, 'banana', 'apple', and 'orange' are keys, and 3, 1, and 2 are their corresponding values.

In Python, the sorting of a dictionary is possible in many ways. Here, we’ll present five such techniques to do this task. Firstly, check the sorted() method which is a built-in Python function.

Method 1: Using the sorted() function

The sorted() function is a built-in Python function that can be used to sort any iterable, including dictionaries. When applied to a dictionary, sorted() returns a list of sorted keys.

# Example using sorted()
di_ct = {'tube': 11, 'bulb': 5, 'led': 7}

# Sort by keys using sorted()
sort_key = sorted(di_ct.keys())

# Print the sorted keys and their respective values
for ki in sort_key:
    print(f'{ki}: {di_ct[ki]}')

In this example, sorted_keys contains the sorted keys, and we iterate through them to access the values in the original dictionary. This method provides a simple and effective way to sort a dictionary by its keys.

Method 2: Using items() method with sorted()

Another approach is to use the items() method along with the sorted() function. This method returns a list of tuples where each tuple contains a key-value pair.

# Example using items() with sorted()
di_ct = {'boll': 1, 'bat': 3, 'pitch': 2}

# Sort by keys using items() and sorted()
sort_items = sorted(di_ct.items())

# Print the sorted key-value pairs
for ki, value in sort_items:
    print(f'{ki}: {value}')

In this example, sorted_items is a list of tuples, and we iterate through them to print the sorted key-value pairs. This method is useful when you need both keys and values in sorted order.

Method 3: Using collections.OrderedDict

Python’s collections module provides an OrderedDict class that maintains the order of the keys in the order they were inserted. We can leverage this feature to sort the dictionary.

from collections import OrderedDict

# Example using OrderedDict
di_ct = {'car': 3, 'jeap': 1, 'truck': 2}

# Create an OrderedDict from the base di_ct
ord_dict = OrderedDict(sorted(di_ct.items()))

# Print the sorted key-value pairs
for ki, value in ord_dict.items():
    print(f'{ki}: {value}')

In this example, ordered_dict is an OrderedDict that maintains the order of the keys based on their sorting. This method is beneficial when you need to maintain the order of the original dictionary.

Method 4: Using the Lambda Function with sorted()

You can use a lambda function to customize the sorting criteria, providing more flexibility. In the following example, we sort the dictionary based on the length of the keys.

# Example using Lambda Function with sorted()
di_ct = {'cat': 3, 'rat': 1, 'fat': 2}

# Sort by key length using a lambda function with sorted()
sort_key = sorted(di_ct.keys(), key=lambda x: len(x))

# Print the final keys with their respective values
for ki in sort_key:
    print(f'{ki}: {di_ct[ki]}')

Here, the key parameter in the sorted() function is a lambda function that returns the length of each key. You can modify the lambda function based on your custom sorting criteria.

Method 5: Using operator.itemgetter()

The Python operator module provides the itemgetter() function, which can be used as an alternative to lambda functions for sorting.

from operator import itemgetter

# Example using itemgetter() with sorted()
di_ct = {'pen': 3, 'ink': 1, 'nib': 2}

# Sort by keys using itemgetter() and sorted()
sort_key = sorted(di_ct.keys(), key=itemgetter(0))

# Print the sorted keys and their respective values
for ki in sort_key:
    print(f'{ki}: {di_ct[ki]}')

Here, itemgetter(0) specifies that the sorting should be based on the first element of each key-value pair (the keys in this case). You can customize the index according to your requirements.

FAQs: Sorting Python Dictionaries

Here are some FAQs for your knowledge.

Q1: Can I sort a dictionary in descending order?

Answer: Yes, for descending order, use the reverse parameter in sorted(). Example:

# Descending order using sorted() with reverse parameter
sorted_keys_desc = sorted(my_dict.keys(), reverse=True)

Q2: How to sort a dictionary based on values?

Answer: For sorting by values, use sorted() with the key parameter. Example:

# Sorting by values using lambda function with sorted()
sorted_items_values = sorted(my_dict.items(), key=lambda x: x[1])

Q3: Can a dict be sorted in place?

Answer: Yes, collections.OrderedDict sorts in place, maintaining key order. Example:

# Sorting in-place using OrderedDict
ordered_dict = OrderedDict(sorted(my_dict.items()))

Q4: How to sort a dict based on a custom criterion?

Answer: Customize sorting using the key parameter in sorted(). Example:

# Sorting by key length using lambda function with sorted()
sorted_keys_length = sorted(my_dict.keys(), key=lambda x: len(x))

Q5: Why choose OrderedDict over other methods?

Answer: Use OrderedDict to maintain insertion order. Example:

# Using OrderedDict to maintain order
ordered_dict = OrderedDict(sorted(my_dict.items()))

Q6: Can these methods handle dicts with different data types?

Answer: Yes, methods work with any comparable data types. Python sorting is versatile. Example:

# Sorting dicts with different data types
sorted_keys = sorted(my_dict.keys())

Experiment and adapt these methods as per your needs.

Conclusion – Sort Dictionary By Key

Congratulations! You’ve now learned multiple methods to sort a dictionary by its keys in Python. Each method has its respective advantages, so choose the one that best fits your needs and the specific requirements of your program. Play with these methods to gain a deeper understanding. Finally, you’ll master the art of efficiently sorting dictionaries in Python.

Happy Coding,
Team TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Soumya Agarwal Avatar
By Soumya Agarwal
Follow:
I'm a BTech graduate from IIITM Gwalior. I have been actively working with large MNCs like ZS and Amazon. My development skills include Android and Python programming, while I keep learning new technologies like data science, AI, and LLMs. I have authored many articles and published them online. I frequently write on Python programming, Android, and popular tech topics. I wish my tutorials are new and useful for you.
Previous Article Python Sort a List in Descending Order With Examples Python Sort a List in Descending Order With Examples
Next Article Python Sort Array Values With Examples Python Sort Array Values With Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x