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 Sorting a Dictionary
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 BasicPython Tutorials

Python Sorting a Dictionary

Last updated: Oct 27, 2023 8:33 pm
By Harsh S.
Share
14 Min Read
Sort a Dictionary in Python
SHARE

Sorting a dictionary in Python allows you to organize its key-value pairs based on certain criteria. It includes sorting by keys or values, in ascending or descending order. Python provides several methods to achieve this. And, in this tutorial, we will explore various methods to sort a dictionary. We’ll also provide code examples and compare the methods to help you choose the most suitable one.

Contents
1. Sorting a Python Dictionary by Keys2. Sort the Python Dictionary by ValueStep-by-Step Explanation3. Sorting in Descending Order4. Custom Sorting of a Dictionary in PythonExplanation:5. Comparing Different Methods6. Sorting a Dictionary In Place7. Sorting a Nested Dictionary in PythonPerformance Considerations

Different Methods to Sort a Dictionary in Python

This tutorial explains how to sort dictionaries in Python by keys or values, in ascending or descending order. Let’s explore the different ways to do this.

1. Sorting a Python Dictionary by Keys

In this section, we demonstrate how to sort a dictionary based on its keys in ascending order. It sets the order alphabetically or in the default order of the keys if they are not strings (e.g., integers, dates).

Also Read: Python OrderedDict Tutorial

Sorting a dictionary by its keys is one of the basic operations. It allows you to arrange data alphabetically or in a custom order based on keys. Let’s dive into an example:

# Sample dictionary with country codes and populations
country_data = {'US': 331002651, 'India': 1380004385, 'China': 1444216107, 'Brazil': 212559417}

# Sort the dictionary by keys in ascending order
sorted_countries = {k: country_data[k] for k in sorted(country_data)}

print(sorted_countries)

The above code sorts the dictionary by keys in ascending order. It produces a new dictionary with the same data, but now alphabetically. After you run It prints the following result:

{'Brazil': 212559417, 'China': 1444216107, 'India': 1380004385, 'US': 331002651}

Let’s take another example that uses the Python lambda function along with the sorted function.

# Create a sample dictionary
my_dict = {'b': 4, 'a': 2, 'd': 8, 'c': 6}

# Sort the dictionary by keys
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[0]))

print(sorted_dict)

This code produces the following output:

{'a': 2, 'b': 4, 'c': 6, 'd': 8}

In this example, we first convert the dictionary items into a list of tuples using items(). Then, we use sorted() to sort these tuples based on their first element (keys) in ascending order. Finally, we convert the sorted list of tuples back into a dictionary.

2. Sort the Python Dictionary by Value

Here, we’ll show how to sort a dictionary based on its values in ascending order. The sorting arranges the dictionary items based on their values, from lowest to highest.

Sometimes, it’s more meaningful to sort a dictionary by its values. For instance, when dealing with sales data, you might want to identify the highest and lowest-performing products. Here’s an example:

# Sample dictionary with product sales data
sales_data = {'Product A': 1500, 'Product B': 2800, 'Product C': 900, 'Product D': 3500}

# Sort the dictionary by values in ascending order
sorted_sales = {k: v for k, v in sorted(sales_data.items(), key=lambda item: item[1])}

print(sorted_sales)

Step-by-Step Explanation

Firstly, the above code is not everybody can understand quickly. This is even harder for us to grasp. But that’s how one can improve his skills by doing complex things.

Anyways, in order to make it easier for you, let’s decode it bit by bit.

  1. {k: v for k, v in ...}: This is known as dictionary comprehension. It’s a concise way to create a new dictionary based on some criteria. Let’s break it down step by step:
    • {}: These curly braces indicate that we’re creating a new dictionary.
    • k: v: This part inside the braces specifies the structure of each key-value pair in the new dictionary. k represents the key (e.g., ‘Product A’), and v represents the value (e.g., 1500).
    • for k, v in ...: This is a loop that iterates over the items in the iterable that follows. In this case, it iterates over the sorted list of key-value pairs created by sorted(sales_data.items(), key=lambda item: item[1]).
  2. sorted(sales_data.items(), key=lambda item: item[1]): This part performs the sorting of the sales_data dictionary based on the values (sales numbers) in ascending order. Here’s how it works:
    • sales_data.items(): This converts the dictionary into a list of key-value pairs (tuples), like ('Product A', 1500), ('Product B', 2800), etc.
    • key=lambda item: item[1]: This lambda function specifies the sorting key. It extracts the second element (item[1]), which is the sales number, from each tuple in the list.
  3. Putting it all together:
    • The sorted() function sorts the list of key-value pairs based on the sales numbers in ascending order.
    • The {k: v for k, v in ...} part creates a new dictionary where, for each pair in the sorted list, k represents the product name (key), and v represents the sales number (value).
  4. Result:
    • After this operation, the sorted_sales dictionary contains the products sorted by their sales numbers in ascending order.

When this code runs, it prints the following result:

{'Product C': 900, 'Product A': 1500, 'Product B': 2800, 'Product D': 3500}

In this Python example, we sort the dictionary by values in ascending order. In this way, it is easy to identify the products with the lowest sales.

3. Sorting in Descending Order

In this section, we’ll sort a dictionary in descending order. This means we’ll reverse the order of either the keys or the values to create a descending arrangement, which is the opposite of the default ascending order.

Sorting in descending order is as simple as adding the reverse=True argument when using the sorted() function. Here’s an example.

# Sample dictionary with product ratings
ratings_data = {'Product X': 4.5, 'Product Y': 3.8, 'Product Z': 4.9, 'Product W': 4.2}

# Sort the dictionary by ratings in descending order
sorted_ratings = {k: v for k, v in sorted(ratings_data.items(), key=lambda item: item[1], reverse=True)}

print(sorted_ratings)

Copy-paste the above code in your Python IDE. After running it, you will get the following result:

{'Product Z': 4.9, 'Product X': 4.5, 'Product W': 4.2, 'Product Y': 3.8}

In this example, we sort the dictionary by ratings in descending order to highlight the products with the highest ratings.

4. Custom Sorting of a Dictionary in Python

Custom sorting allows you to define your sorting criteria. In this section, we’ll explore using the sorted() function with custom sorting keys. You can sort the dictionary based on specific attributes or criteria of the dictionary items. This method provides flexibility in sorting that goes beyond simple key or value sorting.

The sorted() function is a versatile tool for dictionary sorting. You can customize it further by specifying different sorting criteria. Here’s an example demonstrating sorting by keys in descending order:

# Sample dictionary with city temperatures
temperature_data = {'New York': 72, 'Los Angeles': 88, 'Chicago': 65, 'Miami': 92}

# Step 1: Sort the dictionary by city names in descending order
# Custom Sorting Key: City Names
# Purpose: To arrange the cities in reverse alphabetical order based on their names.

# Sorting the dictionary:
sorted_cities = sorted(temperature_data.keys(), reverse=True)

# Creating a new dictionary with custom sorting:
sorted_temperatures = {city: temperature_data[city] for city in sorted_cities}

# Step 2: Print the sorted dictionary

# Finally, we print the `sorted_temperatures` dictionary, which contains the cities
# sorted in descending alphabetical order. Each city name is associated with its
# respective temperature.

print(sorted_temperatures)

Explanation:

Step 1: The code starts with a dictionary temperature_data. It has city names as keys, and their respective temperatures as values.

Custom Sorting Key: City Names

Purpose: To arrange the cities in reverse alphabetical order based on their names.

  • Sorting the Dictionary: Using the sorted() function with reverse=True, we sort the city names in reverse alphabetical order. This provides us with a list of sorted city names, which acts as our custom sorting key.
  • Creating a New Dictionary with Custom Sorting: Next, we create a new dictionary called sorted_temperatures. We iterate through the sorted city names (our custom sorting key) and, for each city, associate it with its respective temperature from the original temperature_data dictionary. This step creates a new dictionary with the custom sorting order.

Step 2: Finally, we print the sorted_temperatures dictionary. It contains the cities sorted in descending alphabetical order, with each city name linked to its corresponding temperature.

As you set to run the code, the following is the output seen.

{'New York': 72, 'Miami': 92, 'Los Angeles': 88, 'Chicago': 65}

5. Comparing Different Methods

Now, let’s compare the methods we’ve discussed for sorting dictionaries:

MethodEase of UsePerformanceSorting CriteriaOutput Order
Sorting by KeysEasyGoodKeysAscending
Sorting by ValuesEasyGoodValuesAscending
Sorting in DescendingEasyGoodKeys/ValuesDescending
Using sorted()EasyGoodCustomizableCustomizable

While these methods work well for small to medium-sized dictionaries, for large datasets, you may want to explore more efficient data structures or algorithms for sorting to improve performance.

Let’s discuss some other ways to sort a dictionary in Python.

6. Sorting a Dictionary In Place

If you want to sort a dictionary in place, you can use the iterkeys() and itervalues() methods. These methods return iterators over the keys and values in the dictionary, respectively.

To sort a dictionary in place, you can iterate over the keys or values in the dictionary and then move the key-value pairs to their desired positions.

# Define a dictionary
my_dict = {'student1': 25, 'student2': 30, 'student3': 28}

# Get the items of the dictionary
items = list(my_dict.items())

# Sort the items by value
items.sort(key=lambda item: item[1])

# Move the key-value pairs to their desired positions
for i in range(len(items)):
    my_dict[items[i][0]] = items[i][1]

# Print the sorted dictionary
print(my_dict)

When you run the above code, it will print the following:

{'student1': 25, 'student2': 30, 'student3': 28}

7. Sorting a Nested Dictionary in Python

A nested dictionary is a dictionary that contains other dictionaries. To sort a nested dictionary, you can use the same methods that you would use to sort a regular dictionary. However, you will need to iterate over the nested dictionaries and sort them individually.

For example, the following code sorts a nested dictionary by key:

# Define a nested dictionary
my_dict = {'student1': {'age': 25, 'occupation': 'software engineer'},
           'student2': {'age': 30, 'occupation': 'data scientist'},
           'student3': {'age': 28, 'occupation': 'product manager'}}

# Sort the nested dictionary by key
def sort_dict_by_key(dict):
    keys = list(dict.keys())
    keys.sort()

    sorted_dict = {}
    for key in keys:
        sorted_dict[key] = dict[key]

    return sorted_dict

# Print the sorted dictionary
sorted_dict = sort_dict_by_key(my_dict)
print(sorted_dict)

Copy-paste the above code in your editor. When you run it, the following is the result.

{'student1': {'age': 25, 'occupation': 'software engineer'}, 'student2': {'age': 30, 'occupation': 'data scientist'}, 'student3': {'age': 28, 'occupation': 'product manager'}}

Also Read – Python Append to a Dictionary

Performance Considerations

When dealing with very large dictionaries, the performance of these methods may degrade. In such cases, consider using specialized data structures like collections.OrderedDict or external sorting algorithms to efficiently handle large datasets.

Conclusion

In conclusion, it is important to realize that sorting dictionaries is a basic skill for any Python programmer.

Whether you’re collecting data for analysis, producing reports, or improving the user experience of your programs, sorting is the key skill.

Try to use the methods shown in this tutorial to fix your sorting approach as per your specific needs. We hope this tutorial has been helpful!

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.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Convert Python Dictionary to JSON Python Dictionary to JSON
Next Article Choose the Best IDE for R Programming Best IDEs for R Programming in 2024

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
x