Image via Midjourney. Prompt: "a computer sorting a dictionary"

Code Snippets: Python – How to sort dictionary values

In this blog post, we will explore two methods to sort dictionary values, demonstrating their implementation and usage.

Introduction

Dictionaries in Python are a powerful data structure that are not just useful to store key pair values, but they can also be sorted to retrieve the information we are looking for in a more efficient way. The default way of sorting dictionaries is by key, either ascending or descending.

Sometimes though, it might be useful to order the data based on their value. In this post we will explore two methods of doing so and By the end of it, you’ll have a clear understanding of how to leverage these techniques to enhance your data manipulation skills in Python.

Method 1: Use a lambda function

One approach to sorting dictionary values is by using a lambda function.

Lambda functions are small anonymous function that can take any number of arguments but only have one expression. In this case, we are going to use them to return the values of the dictionary and then sort them.

Let’s delve into the implementation:

# Sort a Python dictionary by value
# (which means to get a representation of that dictionary sorted by value)
# instead of by key
# Input dictionary
dict_ = {'el_1': 304, 'el_2': 101, 'el_3': 43, 'el_4': 7}

# Using a lambda function to sort the dictionary values
sorted(dict_.items(), key=lambda x: x[1])
# Output: [('el_4', 7), ('el_3', 43), ('el_2', 101), ('el_1', 304)]

Method 2: Leveraging the operator library

Another method involves utilising the operator library and its itemgetter method.

Here’s the code implementation:


import operator # Input dictionary dict_ = {‘el_1’: 304, ‘el_2’: 101, ‘el_3’: 43, ‘el_4’: 7} # Using the operator library and itemgetter method to sort the dictionary values sorted(dict_.items(), key=operator.itemgetter(1)) # Output: [(‘el_4’, 7), (‘el_3’, 43), (‘el_2’, 101), (‘el_1’, 304)]

Conclusion

Sorting dictionary values in Python provides a powerful way to organize data based on specific criteria. By taking advantage of either lambda functions or the operator library, you can easily sort a dictionary’s values in ascending or descending order. Incorporate these methods into your coding repertoire and unlock new possibilities for efficient data manipulation.


Posted

in

by