Loading...

Python Sort Dictionary by Key or Value

What is a Python dictionary? How to create Python dictionary? Is there a way to sort a dictionary in Python?

In this blog, we are going to answer all the questions related to Python dictionaries. We will discuss what is a Python dictionary and how to create a dictionary. We will also explore the different ways to sort Python dictionaries.

An image that shows an example of how to sort a Python dictionary by keys and how to sort the Python dictionary by values.

Apr 10, 2023    By Team YoungWonks *

Introduction to Python dictionaries

Python dictionaries are an incredibly powerful and versatile data structure. They allow you to quickly lookup values based on a key, store multiple values for the same key, and even add new items to the dictionary without having to re-create it from scratch. It's no wonder that Python dictionaries have become such a popular tool for developers!

How to create a Python dictionary?

Throughout this blog / Python tutorial, we will use Python 3 and you can install any version of Python 3. It is highly recommended that you install the latest version of Python 3 to write and run our Python programs.

There are multiple ways to create dictionaries in Python. For beginners, here is an example that shows the simplest syntax to create a Python dictionary:

how to create a python dictionary

In this example, name, gender, and age are the keys. On the other hand, Claudia, female and 24 are their respective values.

Python dictionaries can also be created using the dict() constructor by simply providing a list or tuple of comma-separated key-value pairs. This constructor keeps track of the insertion order of key-value pairs in the dictionary. Before Python 3.6, we used to rely on OrderedDict class of the collections module to keep track of the insertion order in Python dictionaries.

Create Python dictionary using a tuple of key-value pairs

The following example explains how to use the dict constructor with tuple_data to get the data stored inside the my_dict dictionary.

create python dictionary using a tuple of key value pairs

Create Python dictionary using a list of key-value pairs

The following example explains how to use the dict constructor with list_data to get the data stored inside the my_dict dictionary.

create python dictionary using a list of key value pairs

Why use dict () over {}?

The dict() constructor allows developers to create a dictionary from any iterable object, including lists and tuples. This makes it easier for developers to build complex data structures, such as nested dictionaries or multi-level hierarchical dictionaries. It also provides a more robust interface for creating dictionaries, as opposed to just the literal notation of curly braces.

How to sort a dictionary in Python?

Dictionaries are a powerful data structure in Python, providing a convenient way to store and access data using key-value pairs. However, one thing that dictionaries do not natively support is sorting. Sorting data in a dictionary allows us to access data faster and reduce data complexity. In the following sections, we'll explore different ways to sort a Python dictionary that include:

  • sorting a dictionary by keys
  • sorting a dictionary by values

Sorting a dictionary by Keys

The first way we can sort a dictionary is by its keys. This is useful if you want to present the data in a certain order, such as alphabetically. To sort a dictionary by its keys, we can simply use the sorted function and pass in the dictionary as the iterable. The sorted function can sort the keys in ascending or descending order and string in alphabetical order and returns a new list having those keys. By default, the sorted function will sort the keys in ascending order.

Here is an example of sorting dictionary keys in ascending and descending order. When the entire dictionary is given to the sorted function, only the keys are sorted and returned in a new list.

Code to sort keys of Python dictionary

The following example explains how to use the sorted function to get the keys of a dictionary sorted inside the sorted_dict_keys list.

code to sort keys of python dictionary

If we want to sort the keys in reverse order, we can pass in the reverse parameter as True.

Code to reverse sort keys of Python dictionary

The following code explains how to use the reverse parameter of the sorted function to reverse sort the keys of the fruits dictionary.

code to reverse sort keys of python dictionary

We can also use the keys() method to get the keys of a dictionary. The code below shows how to use the keys() method to sort list of keys in a dictionary.

Code to sort keys of Python dictionary using keys() method

code to sort keys of python dictionary using keys method

It's important to note that the sorted function returns a new list of the sorted keys, rather than modifying the dictionary in place. If you want to sort the dictionary completely by using its keys, we'll look at how to do that in the code below.

Here's an example to sort a dictionary by its keys.

Code to sort Python dictionary using dictionary comprehension

code to sort python dictionary using dictionary comprehension

We can also use the items() method to get the dictionary items and sort the dictionary over the keys. Here is an example to sort dictionary keys using the items() method. Let's take an example to understand the working of this method.

The items() method

The following example shows how a dictionary of fruits can be used with the items method to generate dict_items that has pairs of keys and values.

python items method

The above output is a representation of the dictionary that gives us a way to iterate through the dictionary without list generation.

Here is an example to sort dictionaries based on keys.

Code to sort Python dictionary using the items() method

code to sort python dictionary using the items method

Using the items method to sort gives us a dictionary sorted by keys only. This is because the tuples are compared lexicographically, which means the first element in the tuple is given the highest priority. Hence, we need to use extra parameters to sort by values. We will explore the extra parameters needed.

Sorting a Dictionary by Values

Another way we can sort a dictionary is by its values. This is useful if you want to find the keys with the highest or lowest values from the sorted values.

To sort dictionary values, we can use the sorted function along with the items() method of the dictionary. The items method returns a list of tuples, where each tuple consists of a key-value pair. We can then pass this list of tuples to the sorted function and use the key parameter to specify a function that returns the value to be used for sorting. In this case, we can use the lambda function to return the second element of the tuple (the value).

Here is an example of sorting a dictionary by its values.

Code to sort Python dictionary using lambda function

code to sort python dictionary using lambda function

As with sorting by keys, we can also specify the reverse parameter to sort the values in reverse order.

Code to reverse sort Python dictionary using lambda function

code to reverse sort python dictionary using lambda function

Let's look at another example to sort a dictionary based on values.

Code to sort Python dictionary using key attribute

code to sort python dictionary using key attribute

In the above code, we have a function called get_value (created using the def keyword) as the key function to sort the dictionary based on values. The sorted function returns a list of tuples containing the keys and values of the dictionary. We can create a new dictionary and store the keys and values using a for-loop. This gives us a dictionary sorted by values.

Here is another way to sort the dictionary based on values.

Code to sort Python dictionary using itemgetter function

code to sort python dictionary using itemgetter function

The zip function can also be used to sort dictionaries using values.

Code to sort Python dictionary using zip function

code to sort python dictionary using zip function

To learn more about dictionaries, read our other blog: https://www.youngwonks.com/blog/Python-Dictionary-Methods

Frequently asked questions

This section answers some frequently asked questions related to dictionaries.

How do I access a list of dictionary keys?

You can use the keys() method to return a list of all the keys in a dictionary.

What is sorted () in Python? How does key work in sorted?

Sorted() is a built-in function in Python which takes an iterable object as an argument and returns a sorted list containing all of the elements of the iterable object. We can get sorted order of different data types using this function. The key parameter of the sorted() function allows users to specify which parts of each element should be used for sorting.

What is dictionary key rule?

Dictionary keys in Python must be immutable objects, meaning they can't be changed once created. This means that numbers, strings and tuples can all be used as dictionary keys; however, lists cannot be the keys since they are mutable. Having immutable objects as keys makes it easier for the interpreter to process them efficiently.

Enhancing Computational Skills through Python Programming

Mastering the art of sorting dictionaries in Python is a small yet significant step towards becoming proficient in programming. At YoungWonks, we offer coding classes for kids that cover fundamental and advanced concepts in Python, ensuring that students build a solid foundation and continue to excel in their coding journey. Through hands-on projects and engaging lessons in our Python coding classes for kids, young learners will find a conducive environment to explore, learn, and apply programming concepts such as sorting dictionaries, thereby enhancing their problem-solving skills and computational thinking.

*Contributors: Written by Saisumana Perumalla; Edited by Rohit Budania; Lead image by Shivendra Singh

This blog is presented to you by YoungWonks. The leading coding program for kids and teens.

YoungWonks offers instructor led one-on-one online classes and in-person classes with 4:1 student teacher ratio.

Sign up for a free trial class by filling out the form below:



By clicking the "Submit" button above, you agree to the privacy policy
Share on Facebook Share on Facebook Share on Twitter Share on Twitter
help