Sling Academy
Home/Python/Python: How to sort a dictionary by key or value (4 examples)

Python: How to sort a dictionary by key or value (4 examples)

Last updated: February 13, 2024

Overview

Dictionaries in Python are inherently unordered prior to Python 3.7. However, Python 3.7 and later versions remember the order of items inserted. Despite this feature, there are numerous situations where one needs to sort a dictionary by its keys or values for various purposes such as data analysis, organization of information, or simply to improve readability. This article provides a step-by-step guide on how to sort dictionaries in Python using both basic and advanced techniques, topped with multiple examples to illustrate each method.

Sorting by Keys

Sorting a dictionary by its keys is straightforward. The simplest way to achieve this is by using the sorted() function, which returns a list of the sorted keys. You can then use a dictionary comprehension to create a new sorted dictionary.

Example 1: Sorting by keys

my_dict = {'banana': 3, 'apple': 2, 'pear': 1, 'orange': 4}
dict_sorted_by_keys = {key: my_dict[key] for key in sorted(my_dict)}
print(dict_sorted_by_keys)

Outpu:

{'apple': 2, 'banana': 3, 'orange': 4, 'pear': 1}

Sorting by Values

Sorting a dictionary by values requires extracting the values along with keys, sorting them, and then rebuilding the dictionary. You can use a lambda function as the key argument in the sorted() function to achieve this.

Example 2: Sorting by values

my_dict = {'banana': 2, 'apple': 4, 'pear': 1, 'orange': 3}
sorted_by_value = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_by_value)

Output:

{'pear': 1, 'banana': 2, 'orange': 3, 'apple': 4}

Advanced Sorts

For more complex sorting needs, such as sorting by the values but in descending order or sorting based on a custom function, Python offers additional flexibility.

Example 3: Sorting by values in descending order


my_dict = {'banana': 2, 'apple': 4, 'pear': 1, 'orange': 3}
sorted_descending = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_descending)

Output:

{'apple': 4, 'orange': 3, 'banana': 2, 'pear': 1}

In advanced scenarios, you might want to sort dictionaries based on a custom logic. One common practice is to sort a dictionary by the length of its keys. This can be achieved by passing an appropriate function to the sorted() key parameter.

Example 4: Sorting by the length of the keys


my_dict = {'banana': 3, 'a': 5, 'pear': 2, 'orange': 4}
sorted_by_key_length = dict(sorted(my_dict.items(), key=lambda item: len(item[0])))
print(sorted_by_key_length)

Output:

{'a': 5, 'pear': 2, 'banana': 3, 'orange': 4}

The versatility of sorting mechanisms in Python allows for myriad sorting practices beyond what’s detailed here, such as sorting by composite keys or applying secondary sort criteria. As you delve deeper into Python’s capabilities, you’ll discover even more sophisticated methods for sorting dictionaries to fit any scenario.

Conclusion

Sorting dictionaries by keys or values in Python is not merely for esthetic optimization but often a necessity for data manipulation and analysis. With the understanding of basic to advanced sorting methods outlined in this article, you’re now equipped to handle a wide array of sorting requirements, enhancing your Python scripts’ efficiency and readability. Remember, the simplicity or complexity of the method chosen should align with the specific needs of your project or task.

Next Article: Python: How to update a list value in a dictionary

Previous Article: Python: Delete items from a dictionary using a list of keys (4 ways)

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots