Sort a Dictionary by Value

Python: Sort a Dictionary by Value

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Examples:

Sorting values in ascending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

Sorting values in descending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

Sort a Dictionary by Value in Python

1)Sorted() function

Sorting any sequence in Python is a breeze thanks to the built-in method sorted(), which does all of the heavy lifting for you.
Sorted() sorts any sequence (list, tuple) and always returns a list with the elements sorted in the same order as the original sequence.

Syntax:

sorted(iterable, key, reverse)

Parameters:

sorted accepts three parameters, two of which are optional.

Iterable:  a sequence (list, tuple, or string) or a collection (dictionary, set, or frozenset) or any other iterator that must be sorted.
Key(optional):   A function that can be used as a key or as the basis for sort comparison.
Reverse(optional):   If set to true, the iterable is sorted in reverse (descending) order; otherwise, it is set to false.

2)Using sorted() +items() + Lambda function

We’ll use the sorted() function and transfer a key function that returns the first index element of the tuple, i.e. the value field from the key/value pair, to sort dictionary elements by value.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1]):
    # print key and value
    print(i[0], ":", i[1])

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

3)Using sorted() +items() + Lambda function to sort in reverse order

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1], reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

4)Using sorted() +items() + itemgetter in Python

To achieve similar functionality, Itemgetter can be used instead of the lambda function. The same as sorted() and lambda, but with a different internal implementation. It takes dictionary keys and converts them to tuples. It reduces overhead while also being faster and more efficient. To function, the “operator” module must be imported.

The itemgetter object can be passed as a key argument to the sorted() function to retrieve the value field from each key-value item of the dictionary while sorting.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1)))
# print dictionary
print(dictionary)

Output:

{'is': 20, 'Platform': 25, 'this': 70, 'BTechGeeks': 100}

5)Using sorted() +items() + itemgetter  to sort in descending order in Python

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1), reverse=True))
# print dictionary
print(dictionary)

Output:

{'BTechGeeks': 100, 'this': 70, 'Platform': 25, 'is': 20}

Related Programs: