Python Sort Dictionary by Key and Value with Example

What are dictionary keys?

The dictionary key/s are from a Python object or part of an argument in a program.

A Python dictionary is a collection of key-value pairs in which each key corresponds to a value.

A key-value pair’s value may be an integer, text, list, tuple, or even another dictionary.

Additionally, you can use any acceptable Python type for the value of the key-value combination.

Nevertheless, a dictionary key always has its corresponding value as you can see in actual dictionaries.

What do KEYS () do in Python?

Python’s keys () function is used to retrieve all of the dictionary’s keys.

The keys must be unique and of an immutable type (string, integer, or tuple with immutable members).

The Python key() function is different from the key that we call or sort from the dictionary.

The function of the key is specifically applicable to returning a key from the dictionary.

However, in some cases, programmers want to sort Python keys in a dictionary which is why we use other functions.

Why Sorting Needed in the Dictionary?

Sorting is very much needed in Python dictionary for the following reasons:

  • Sorting could help programmers handle large amounts of data in dictionaries.
  • The sort() function enables Python programmers to create queries that sort data by value and keys.
  • Sorting also reduces data complexity which makes the dictionary efficient and easy to read.

We have the following ways how to sort Python dictionaries by key and values:

  1. Sort keys key_value.iterkeys() function.
  2. Sort keys through the (key_value) function. This function enables you to print the values of each key.
  3. The key_value.iteritems() function is also able to sort data alphabetically.
  4. You may also use the key = lambda (k, v) : (v, k)) function to sort and display keys and values.

Important things you need to do to sort a dictionary in Python by value and key

  • The first task is to create a dictionary and alphabetically display its list keys.
  • The next thing is to display both the dictionary keys and values in the output. These keys and values must be sorted in alphabetical order.
  • Lastly, you can try to sort the dictionary by keys or values and display it as output.

How to Sort Dictionary by key in Python

The following are the methods to sort dictionary by key.

1. Displaying the Keys in Sorted Order

In this example, we will try first how to sort the keys in a Python dictionary without displaying its values.

Example:

def Dictionary():
	keylists = {2: 4, 4: 8, 6: 12, 8: 16, 10: 20, 12: 24}

	for i in sorted(keylists.keys()):
		print(i, end=" ")


def main():
	Dictionary()
main()

Output:

2 4 6 8 10 12

The output shows the sorted key from the Python dictionary. To sort it from the Python dictionary, the iterkeys() function is used.

It is presented as i in the program and it returns all the keys from the given inputs.

The for i in sorted(keylists.keys()): is the function that really sorts the key from the Python dictionary. While print(i, end=” “) invokes the program to arrange the keys from lowest value to highest and displays the output.

2. Sort the dictionary by key

This example will try to sort the key in the Python dictionary in lexicographic order which will display such as in actual dictionaries.

Example:

from collections import OrderedDict
 
dict = {'Paul': '22', 'Prince': '24', 'Grace': '23', 'Gladys': '22'}

print(OrderedDict(sorted(dict.items())))

Output:

OrderedDict([('Gladys', '22'), ('Grace', '23'), ('Paul', '22'), ('Prince', '24')])

In this example, the program sorts the Python keys (names) in the dictionary order. The outputs then display the keys along with their corresponding values.

OrderedDict is a Python subclass under the built-in file “collections”. This subclass has the dict declaration which is understood as a Python dictionary.

The print(OrderedDict(sorted(dict.items()))) enables the program to sort and display the keys under the subclass.

3. Sorting the Keys and Values in Alphabetical Order

The next example will try to show you how to sort Python keys and values in a dictionary. This will sort the keys in alphabetical order along with their values.

Example:

def Dictionary():
    
    keylists = {2: 24, 4: 12, 6: 12, 8: 10, 10: 2, 12: 8}
    
    for i in sorted(keylists):
        print((i, keylists[i]), end=" ")

def main():
    Dictionary()
main()

Output:

(2, 24) (4, 12) (6, 12) (8, 10) (10, 2) (12, 8)

The outputs justify how the function sorts the keys in the Python dictionary.

It does not literally mean alphabetically arranged but the concept is it displays the keys in order (lowest to highest) and their values.

The functions of each program line were the same as the explanation in the first example.

The only difference is their outputs wherein the output of the former example does not include the values.

4. Sorting the Keys and Values in alphabetical using the value

This example will now show how to sort keys based on their values within the Python dictionary.

Basically, the output should be based on the values of each key in the form of lowest to highest order.

Example:

def Dictionary():
    
    keylists = {2: 24, 4: 12, 6: 12, 8: 10, 10: 2, 12: 8}
    
    print(sorted(keylists.items(), key=lambda kv:
                 (kv[1], kv[0])))

def main():
    Dictionary()
main()

Output

[(10, 2), (12, 8), (8, 10), (4, 12), (6, 12), (2, 24)]

As you see in the output, this shows the lowest to highest order of the dictionary based on its values.

When this function is applied to strings, it will show an alphabetical order of strings as an output.

5. Sort Dictionary By Value in Python

The example below shows how the function works with string as key and integers as their values.

This will sort the Python keys within a dictionary from lowest to highest (alphabetical) based on their values.

This means that the output should display a series of dictionaries with their values arranged from lowest to highest.

Example:

import numpy
from collections import OrderedDict
 
dict = {'Paul': '22', 'Prince': '24', 'Grace': '23', 'Gladys': '22'}

sortedValue = numpy.argsort(dict.values())
keys = list(dict.keys())
sortedDict = {keys[i]: sorted(
    dict.values())[i] for i in range(len(keys))}
 
print(sortedDict)

Output:

OrderedDict([('Gladys', '22'), ('Paul', '22'), ('Grace', '23'), ('Prince', '24')])

The output proves that the keys were sorted according to their values.

Their values were arranged from lowest to highest, therefore the keys were placed when their value belonged.

Summary

In summary, we covered every detail of the topic of how to do Python sort dictionary by key and values with complete discussion and examples.

Furthermore, you also discovered the important task of how to perform the Python sort dictionary by key and by values.

You may also try the given discussion and tutorials on how to implement sorting Python dictionaries.

But if you want to clarify any of the discussed terms or topics, you can always keep us informed through the comments.

Leave a Comment