What is the best way to sort Python dictionary by Value

Data structure dictionary in Python before 3.7 version has no particular order, which makes the process of sorting a tedious job for most beginners

Sorting data is not a new thing for us. We perform this operation as we buy products online, set official and unofficial appointments, or simply stack our wearables in a wardrobe.

When it comes to programming, dictionaries or hash are no different from these setups. These maps or dictionaries are integral to data structures in any given programming language.

Most of the time, people use them to store their data as their keys and values, making a lot of sense instead of building dozens of arrays. In python, sorting a dictionary by Value is usually not straightforward.

However, you can get a representation of a dictionary that is sorted.

The following methods will help you sort dictionaries in python 2.7 or Python 3.X in just a couple of minutes. So, let’s take a look at them!

What is the best way to sort Python dictionary by Value

How Can We Explain Dictionary with Examples?

A dictionary is a particular set or group of data with specified numeric or keys. In programing languages other than python, they have also been termed hash maps or associative arrays.

Generally speaking, they allow us to work with key-value pairs, just like a real-world dictionary.

To create a dictionary, start with a left brace, add your key and type a colon. After that, input your corresponding Value. For multiple key-value pairs, separate them by incorporating a comma.

Once you completely entered your data, close the code with the aid of a right brace.

Example Code

Let’s take a dictionary object which is specified as country population. On the side of it, there are three pairs of keys and values. The keys here will be the countries’ names, such as China, France, and the USA. While the values will be the for each country. Using python, we can summarize it as

countryPopulation = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
print(countryPopulation)

#output 
{'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}

Best Ways to Sort a Dictionary

  • A dictionary can be sorted into various ways; however, one of the common types includes;
  • Sorting dictionary based on values
  • Sorting it on behalf of input keys
  • Using strings to sort the data
  • Reversing the order

Python sort dictionary by Value descending and key ascending

Programmers use the Python sort dictionary by Value more commonly as compared to keys. The following methods will help you out during this kind of procedure.

1)  Using the sort() with the corresponding Dictionary

One of the best ways to sort either key or values in any python dict is by utilizing the sort() functionality. This is the built-in list method that can get you the desired results in no time.

To comprehend this, we will be using a new dictionary termed MarksDict, in which there are names of 4 students, along with their dedicated marks(values).

['1_393_000_000', '328_200_000', '67_000_000']

For sorting the list in terms of Value, just type sorted(MarksDict.values()) in the command section and hit Enter. This will categorize their respective values in a list format.

markDict = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
sorted(MarksDict.values()) 

# output
['1_393_000_000', '328_200_000', '67_000_000']

It is worth noting that the given values are in descending order. To alter that, add reverse=True command inside the values() and run the program again.

markDict = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
sorted(MarksDict.values(), reverse=True) 

# output
['67_000_000', '328_200_000', '1_393_000_000']

2)  Using Lambda functionality in sorted() comprehension

Ascending

In this method, we will be utilizing a ‘dictionary’ comprehension under the input of the lambda function. Using the original dictionary, we will be sorting values in a single line.

So, first of all, enter the print statement and then add the key-value pairs. After that, input the “for” loop, which will iterate the individual items in the dictionary and insert the sort function.

markDict = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
print({k:v for k,v in sorted(markDict.items(), key=lambda item: item[1])})

#output
{'China': '1_393_000_000', 'USA': '328_200_000', 'France': '67_000_000'}

Note that inside the sort function, there is a lambda function. The main reason for the key argument with the item value of 1 is that we are sorting the dictionary based on values. If somehow you need the output for keys, then you should change it to 0.

Descending

If you want to categorize the dictionary in descending format, you simply need to use the reverse statement and turn its Value to True.

markDict = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
print({k:v for k,v in sorted(markDict.items(), key=lambda item: item[1], reverse=True)})

#output
{'France': '67_000_000', 'USA': '328_200_000', 'China': '1_393_000_000'}

3)  Managing itemgetter

For those using an older version of python, this method can be extremely beneficial. An itemgetter is basically a built-in utility residing in the operator module that confronts different sorts of iterables, including sets or tuples, and in turn aids in constructing a callable.

So, to use this method, we first need to import the sequence from the operator as,

import operator
markDict = {'USA': '328_200_000', 'France': '67_000_000', 'China': '1_393_000_000'}
marklist = sorted(markDict.items(), key=operator.itemgetter(1))
sortdict = dict(marklist)
print(sortdict)

#output
{'China': '1_393_000_000', 'USA': '328_200_000', 'France': '67_000_000'}

Again, the context value is set to 1, while the itemgetter acts as the main operator. Running the sequence, we get the following result.

Why Do We Need to Use a Dictionary?

A Python dictionary’s main function is to easily access desired data that is incorporated with a particular key. Its key-value pairs are unique in the way, just like a real-world dictionary.

Usually, a dictionary is unordered and acts as a map in storing that data. Thus, it behaves as a non-complicated tool for any programmer. Some of the key features of hash-maps are,

Note: In Python 3.7, the dictionary is guaranteed order.

  • It can be easily indexed
  • It comes unordered
  • Its key-value pairs are mutable

Conclusion

These were some of the common ways to sort a dictionary by Value in python 3 or older versions. We have also discussed some of the basics of a dictionary, how you can create and use it to derive your data in no time.

In conclusion, sorting a python dictionary by Value can be a bit complicated compared to categorizing it in terms of keys. However, if you follow these sequences without any syntax errors, you will be good to go!

About Haris Khan

Haris is an undergrad student who is enthusiastic about writing, especially writing about tech-related stuff. His main goal is to provide friendly as well as easily digestible content for his viewers.