Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to sort a dictionary by value in Python

Dictionaries in Python: A Quick Recap

Before we jump into sorting dictionaries in Python, let's first understand what a dictionary is. A dictionary is a built-in data type in Python. It's a collection of key-value pairs. Think of it like an actual dictionary. The word you look up (the key) has a corresponding definition (the value).

For example, let's consider a simple dictionary:

student_grades = {'John': 85, 'Emily': 92, 'Lucas': 88, 'Sophia': 90}

Here, the student names are keys and the grades are values.

The Need for Sorting

Now, you might wonder, "Why would I need to sort a dictionary?" Well, imagine you're a teacher, and you want to know which student got the highest grade, or maybe you want to rank the students according to their grades. That's when sorting comes into play!

Sorting by Keys

Before we sort by values, let's understand how to sort by keys. Python has a built-in function sorted() that can help us with this. Here's how you can use it:

student_grades = {'John': 85, 'Emily': 92, 'Lucas': 88, 'Sophia': 90}
sorted_grades = dict(sorted(student_grades.items()))

print(sorted_grades)

When you run this code, you'll see that our dictionary is now sorted alphabetically by student names (keys).

Sorting by Values

Now that we've sorted by keys, let's sort by values. Unfortunately, there's no direct method to do this, but we can utilize the sorted() function with a bit of extra magic. Here's how:

student_grades = {'John': 85, 'Emily': 92, 'Lucas': 88, 'Sophia': 90}
sorted_grades = dict(sorted(student_grades.items(), key=lambda item: item[1]))

print(sorted_grades)

In this code, key=lambda item: item[1] might seem a bit intimidating, but it's not that complex. It's a function that tells Python how to sort our dictionary. item[1] means we're sorting by the second element (values) of our key-value pairs.

Understanding Lambda Functions

The lambda keyword is used to declare small anonymous functions. They're functions without a name. lambda item: item[1] is a function that takes in an 'item' (a key-value pair in our case) and returns the second element (the value).

Think of this function as a tiny helper who's job is to look at each key-value pair and return the grade. Python then uses these grades to sort the dictionary.

What if We Want Descending Order?

The sorted() function by default sorts in ascending order. But what if we want to sort our dictionary in descending order? Luckily, sorted() has an optional parameter called reverse. If it's set to True, our list will be sorted in descending order. Here's how you can do it:

student_grades = {'John': 85, 'Emily': 92, 'Lucas': 88, 'Sophia': 90}
sorted_grades = dict(sorted(student_grades.items(), key=lambda item: item[1], reverse=True))

print(sorted_grades)

Conclusion: Sorting is Just the Beginning

Congratulations! You now know how to sort a dictionary by value in Python. It's a handy tool to have in your Python toolkit. But remember, sorting is just the beginning. Python offers a plethora of built-in functions and data types to make your coding life easier. So, keep exploring, keep learning, and remember, the key to mastering programming (or anything, really) is patience and practice. Happy coding!