Open In App

Python | Sort Python Dictionaries by Key or Value

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.

Need for Sorting Dictionary in Python

We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Sorting is very important when we are dealing with a large amount of data. 

We can sort a dictionary by values using these methods:

  • First, sort the keys alphabetically using key_value.iterkeys() function.
  • Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
  • Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))

Sort Python Dictionaries by Key or Value Examples

Here are the major tasks that need to be performed to sort a dictionary by value and keys in Python.

  1. Create a dictionary and display its list-keys alphabetically.
  2. Display both the keys and values, sorted by key in alphabetical order.
  3. At last, display both the keys and values, sorted by value in alphabetical order.

Example 1: Sorting Dictionary By Key

In this example, we will sort the dictionary by keys and the result type will be a dictionary. 

Python
myDict = {'ravi': 10, 'rajnish': 9,
        'sanjeev': 15, 'yash': 2, 'suraj': 32}

myKeys = list(myDict.keys())
myKeys.sort()
sorted_dict = {i: myDict[i] for i in myKeys}

print(sorted_dict)

Output
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32, 'yash': 2}


Example 2: Displaying the Keys in Sorted Order

In this example, we are trying to sort the dictionary by keys and values in Python. Here, iterkeys() returns an iterator over the dictionary’s keys.

Python
# Function calling
def dictionary():
    # Declare hash function
    key_value = {}

# Initializing value
    key_value[2] = 56
    key_value[1] = 2
    key_value[5] = 12
    key_value[4] = 24
    key_value[6] = 18
    key_value[3] = 323

    print("Task 1:-\n")

    print("key_value", key_value)

    # iterkeys() returns an iterator over the
    # dictionary’s keys.
    for i in sorted(key_value.keys()):
        print(i, end=" ")


def main():
    # function calling
    dictionary()


# Main function calling
if __name__ == "__main__":
    main()

Output
Task 1:-

key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
1 2 3 4 5 6 


Example 3: Sorting the dictionary by key 

In this example, we will sort in lexicographical order Taking the key’s type as a string.

Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict

dict = {'ravi': '10', 'rajnish': '9',
        'sanjeev': '15', 'yash': '2', 'suraj': '32'}
dict1 = OrderedDict(sorted(dict.items()))
print(dict1)

Output
OrderedDict([('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj', '32'), ('yash', '2')])


Example 4: Sorting the Keys and Values Alphabetically Using the Key

In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using an iterator over the Dictionary’s value to sort the keys.

Python
# function calling
def dictionairy():

    # Declaring the hash function
    key_value = {}

# Initialize value
    key_value[2] = 56
    key_value[1] = 2
    key_value[5] = 12
    key_value[4] = 24
    key_value[6] = 18
    key_value[3] = 323
    
    print("key_value",key_value)

    print("Task 2:-\nKeys and Values sorted in",
          "alphabetical order by the key  ")
    

    # sorted(key_value) returns a sorted list
    # of the Dictionary’s keys.
    for i in sorted(key_value):
        print((i, key_value[i]), end=" ")


def main():
        # function calling
    dictionairy()


# main function calling
if __name__ == "__main__":
    main()

Output
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
Task 2:-
Keys and Values sorted in alphabetical order by the key  
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) 


Example 5: Sorting the Keys and Values Alphabetically Using the Value

In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order.

Python
# Function calling
def dictionairy():

    # Declaring hash function
    key_value = {}

# Initializing the value
    key_value[2] = 56
    key_value[1] = 2
    key_value[5] = 12
    key_value[4] = 24
    key_value[6] = 18
    key_value[3] = 323
    
    print("key_value",key_value)

    print("Task 3:-\nKeys and Values sorted",
          "in alphabetical order by the value")

    # Note that it will sort in lexicographical order
    # For mathematical way, change it to float
    print(sorted(key_value.items(), key=lambda kv: 
                 (kv[1], kv[0])))


def main():
    # function calling
    dictionairy()


# main function calling
if __name__ == "__main__":
    main()

Output
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
Task 3:-
Keys and Values sorted in alphabetical order by the value
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]


The time complexity for this program is O(n log n), where n is the number of key-value pairs in the dictionary.

The auxiliary space complexity for this program is also O(n), where n is the number of key-value pairs in the dictionary. 

Example 6: Sorting Dictionary By Value 

In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values.

Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict
import numpy as np

dict = {'ravi': 10, 'rajnish': 9,
        'sanjeev': 15, 'yash': 2, 'suraj': 32}
print(dict)

keys = list(dict.keys())
values = list(dict.values())
sorted_value_index = np.argsort(values)
sorted_dict = {keys[i]: values[i] for i in sorted_value_index}

print(sorted_dict)

Output:

{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
{'ravi': 2, 'rajnish': 9, 'sanjeev': 10, 'yash': 15, 'suraj': 32}

Time complexity: O(n log n), where n is the number of items in the dictionary.
Auxiliary space: O(n), as we are creating new lists of keys and values, and creating a new dictionary with the same number of entries as the original dictionary.

We have covered different examples based on sorting dictionary by key or value. Reading and practicing these Python codes will help you understand sorting in Python dictionaries.

You can easily sort the values of dictionaries by their key or value.

Similar Reads:

Python | Sort Python Dictionaries by Key or Value – FAQs

How to check if key and value match in dictionary Python?

You can check if a key-value pair exists in a dictionary using the in keyword:

my_dict = {'name': 'Alice', 'age': 30}
# Check if key-value pair exists
if 'name' in my_dict and my_dict['name'] == 'Alice':
print("Key 'name' has value 'Alice'")

Does order of keys matter in dictionary Python?

In Python versions before 3.7, the order of keys in a dictionary was not guaranteed to be maintained. However, from Python 3.7 onward, dictionaries preserve the insertion order of keys. This means that the order in which key-value pairs are added to a dictionary is maintained when iterating over the dictionary.

How to extract key and value from list of dictionary in Python?

You can iterate through a list of dictionaries and extract keys and values using a loop:

list_of_dicts = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
for d in list_of_dicts:
for key, value in d.items():
print(f"Key: {key}, Value: {value}")

How do I print a specific key and value in a dictionary Python?

You can directly access a specific key’s value using square brackets []:

my_dict = {'name': 'Alice', 'age': 30}
# Print specific key and value
print(f"Name: {my_dict['name']}, Age: {my_dict['age']}")

How to check if key and value exist in dictionary Python?

You can use the in keyword to check if a key exists in a dictionary, and then verify its corresponding value if needed:

my_dict = {'name': 'Alice', 'age': 30}
# Check if key exists
if 'name' in my_dict:
# Check if key has a specific value
if my_dict['name'] == 'Alice':
print("Key 'name' exists and has value 'Alice'")
else:
print("Key 'name' exists but does not have value 'Alice'")
else:
print("Key 'name' does not exist in the dictionary")

How do I sort a dictionary by value when the values are strings?

You can sort a dictionary by its values, even if they are strings, using the sorted() function with a custom key based on the values:

my_dict = {'apple': '30', 'banana': '20', 'cherry': '10'}
# Sort dictionary by values (strings converted to integers for numeric comparison)
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: int(item[1]))}
print(sorted_dict)

In this example, sorted() sorts the dictionary my_dict by converting the string values to integers (int(item[1])) for numeric comparison. Adjust the key function (lambda item: int(item[1])) based on the specific type or format of your dictionary values.



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Python | Segregating key's value in list of dictionaries
While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using generator expression A generator expression can be use
6 min read
Python - Extract Key's value from Mixed Dictionaries List
Given a list of dictionaries, with each dictionary having different keys, extract value of key K. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'b' Output : 7 Explanation : Value of b is 7. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'c' Output : 11 Ex
7 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python - Extract dictionaries with Empty String value in K key
Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key. Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" Output : [] Explanation : No "Gfg" key is empty. Input : test_list = [{"Gfg" : "", "is" : "good", "best" : "1"}, {"G
8 min read
Python Filter List of Dictionaries Based on Key Value
Python, a versatile and powerful programming language, offers multiple ways to manipulate and process data. When working with a list of dictionaries, you may often need to filter the data based on specific key-value pairs. In this article, we will explore three different methods to achieve this task: using list comprehension, the filter function, a
3 min read
Select Only Specific Key-Value Pairs From a List of Dictionaries
We can select only specific key-value pair from a list of dictionaries by filtering the given dictionaries using any key. If key is present in the dictionary, then it will return the key-value pair. In this article, we will see how we can select only a specific key-value pair from a list of dictionaries. Below is an example showing the input and ou
2 min read