Technology

How to Sort a Dictionary by Value in Python

To sort a dictionary by value in Python you can use the sorted() function. Python’s sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse.


Dictionaries are unordered data structures. They use a mapping structure to store data. Dictionaries map keys to values, creating pairs that hold related data.

Using the Python sorted() method, you can sort the contents of a dictionary by value. For instance, to rank the popularity of items on a coffee menu, or list those items in alphabetical order, you can use Python’s sorted() method. This tutorial will discuss how the sorted() method works and how you can use it to sort the contents of a dictionary. 

Python sorted() Refresher

Python’s built-in sorted() function can be used to sort iterable objects by a key, such as lists, tuples, and dictionaries. The sorted() function sorts the items of the specified iterable object and creates a new object with the newly sorted values.

Here’s the syntax for the sorted() method:

sorted(object, key, reverse)

The method takes in three parameters:

  • object: the iterable object that you want to sort (required)
  • key: the function that allows you to perform custom sort operations (optional)
  • reverse: specifies whether the object should be sorted in descending order (optional)

As you can see, “object” is the only required parameter. If you decide not to use the optional “key” and “reverse” parameters, Python will automatically sort the object in ascending order.

Note: Career Karma wrote a full guide on the sort() and sorted() methods in Python. If you’re looking to learn more about this method and the key parameter, check out our Python sort() tutorial.

Let’s walk through a quick example to illustrate how the sorted() method works. 

Say that we are operating a coffee shop and we want to retrieve an alphabetical list of our Coffee Club (loyalty) customers. We already have a list of customers, but it is ordered by sign-up date. We could use the following code to sort our list:

customers = ['Kaley Fernandez', 'Darius Rowland', 'Isaac Borthwick',  'Alexandria Kidd']
sorted_customers = sorted(customers)
print(sorted_customers)

Our code sorts the customers array and returns the following:

['Alexandria Kidd', 'Darius Rowland', 'Isaac Borthwick', 'Kaley Fernandez']

On the first line of our code, we declare a list that stores our customers’ names; this list is called: customers. Then, we use the sorted() method to sort the list of customer names in ascending order; this new list is called: sorted_customers. Finally, we print out the newly sorted list to the console using the print() function.

Sort a Dictionary by Value

Let’s say that you have a dictionary and you want to sort it by key-value pairs. You can do this by using two functions together: items() and sorted()

The items() function allows you to retrieve the items in a dictionary. We can use this function in combination with the sorted() function and a custom key parameter to sort a dictionary by value. Consider the following two examples.

Example 1: Sort in Descending Order

Let’s return to the coffee shop. Suppose we have a dictionary that stores the items on our coffee menu as well as how many of each item were ordered in the last month. We want to see what the most popular coffee was last month, so we decide to sort the order dictionary in descending order of values.

Here’s a program we could use to sort the contents of our dictionary by value:

orders = {
	'cappuccino': 54,
	'latte': 56,
	'espresso': 72,
	'americano': 48,
	'cortado': 41
}

sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)

for i in sort_orders:
	print(i[0], i[1])

Our code returns the following:

espresso 72

latte 56

cappuccino 54

americano 48

cortado 41

There’s a lot going on in our code, so let’s break it down. 

At the start of our code, we define a dictionary called orders that stores the names of coffees as keys and the number sold as values.

Then, we use the sorted() method to sort the orders dictionary by value. Here’s a breakdown of how we used the sorted() method:

ParameterTextDescription
objectorders.items() Refers to all values in our “orders” dictionary. If we were to use just “orders”, we would have to reference the index position of the item to get its individual value. Whereas if we use orders.items(), an iterable list with the items in a list is created.
keykey=lambda x: x[1]A sorting mechanism that allows us to sort our dictionary by value. This is an example of a Lambda function, which is a function without a name.
reversereverse=TrueStates that we want our data to be sorted in descending order.

Finally, we create a for loop that loops through each item created in our sort_order method and prints out both its key name and its value, sorted in the order we specified in the sort_order function.

Example 2: Sort in Ascending Order

Similarly, if we wanted to find out the least popular drink sold at our coffee shop, we could use the same code as above but without the reverse=True parameter. Here’s an example of the code for this:

orders = {
	'cappuccino': 54,
	'latte': 56,
	'espresso': 72,
	'americano': 48,
	'cortado': 41
}

sort_orders = sorted(orders.items(), key=lambda x: x[1])

for i in sort_orders:
	print(i[0], i[1])

When we run our code, the following values are returned:

cortado 41

americano 48

cappuccino 54

latte 56

espresso 72

As you can see, our code returned a list of items arranged in ascending order, based on the number of each item ordered in the last month.

List Comprehension

In addition, we can use list comprehension to sort dictionary contents by value. List comprehension is a concise technique to create lists in Python and can save space if you are creating more complex sort methods.

Here’s the code we would use to sort our coffee orders in ascending order by the number of each coffee that was ordered using list comprehension:

orders = {
	'cappuccino': 54,
	'latte': 56,
	'espresso': 72,
	'americano': 48,
	'cortado': 41
}

[print(key, value) for (key, value) in sorted(orders.items(), key=lambda x: x[1])

When we run our code, the following response is returned:

cortado 41

americano 48

cappuccino 54

latte 56

espresso 72

The result of our code was the same as our above example where we sorted the contents of the orders list in ascending order. But instead of defining a sort_orders variable and creating a separate for loop to iterate through the sorted list, we created a list using the list comprehension technique.

The list comprehension we created above sorts through each item in our list in ascending order, then prints out the key and value of each dictionary item to the console.

Conclusion

When you’re working with dictionaries in Python, sorting a dictionary by value is a common operation. The sorted() method allows you to sort a set of data based on your needs.

This tutorial discussed, providing examples, how to use the sorted() method to sort a dictionary by value in Python, including how to use the key and reverse parameters. 

Now you’re ready to start sorting dictionaries by value like a Python pro!

Click to rate this post!
[Total: 0]
Subscribe Our Newsletter Don't worry. We wont spam you.

Author

The Articledesk Editorial team is responsible for this post. For collaborations and partnership requests, kindly send an email to the Editorial Team at contact[at]articledesk[dot]net for the terms and conditions. You can also follow Articledesk.net on Twitter here and like our page on Facebook here.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Login for fast comment.

Login

close

About Us

We ensure that current articles are collected at one table for all writers and blog readers.

Follow Us