Python : How to Sort a Dictionary by Key or 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.

In this post, we will look at how to sort a dictionary by key or value

Examples:

By keys

Input:

dictionary = {'this': 200, 'is':100, 'BTechGeeks':300}

Output:

BTechGeeks : 300
is : 100
this :200

Input:

dictionary = {'this': 100, 'is':200, 'BTechGeeks':300}

Output:

is : 100
this : 200
BTechGeeks : 300

Sort a Dictionary by Key/Value

There are several ways to sort a dictionary by key or value some of them are:

Sort Dictionary by keys:

Method #1: Using items() function

A view object is returned by the items() method. The object view contains the dictionary’s key-value pairs as tuples in a list.

The object displays any modifications made in the dictionary.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list
for i in sorted(dictitems):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 300
is : 100
this :200

Method #2:Using dict.keys() method

  • Convert the keys of the dictionary to list .
  • Sort the list .
  • Print the corresponding keys and values as you traverse the list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using dict.keys
dictlist = list(dictionary.keys())
# sort the list
dictlist.sort()
# Print the corresponding key and value by traversing this list
for key in dictlist:
    # print key and value
    print(key, ":", dictionary[key])

Output:

BTechGeeks : 300
is : 100
this :200

Method #3: Sorting the dictionary keys in reverse order

Both of the previous solutions sorted the dictionary ascending order by key. What if we were to sort the contents by the keys in decreasing 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': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in descending order
for i in sorted(dictitems, reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

this : 200
is : 100
BTechGeeks : 300

Sort Dictionary by Values:

Using sorted() and items() functions to sort dictionary by value

We’ll use the same 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': 200, 'is': 100, 'BTechGeeks': 300}
# 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 : 100
this : 200
BTechGeeks : 300

Using sorted() + items() +reverse() functions to sort dictionary by value 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': 200, 'is': 100, 'BTechGeeks': 300}
# 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 : 300
this : 200
is : 100

Related Programs: