Open In App

Python | Sort a Dictionary

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python, Given a dictionary, perform sort, basis on keys or values. [ applicable Python >=3.6v ].

Input : test_dict = {“Gfg” : 5, “is” : 7, “Best” : 2} Output : {‘Best’: 2, ‘Gfg’: 5, ‘is’: 7}, {‘is’: 7, ‘Gfg’: 5, ‘Best’: 2} Explanation : Sorted by keys, in ascending and reverse order. Input : test_dict = {“Best” : 2, “for” : 9, “geeks” : 8} Output : {‘Best’: 2, ‘Gfg’: 5, ‘for’: 9}, {‘for’: 9, ‘geeks’: 8, ‘Best’: 2} Explanation : Sorted by values, in ascending and reverse order.

Case 1 : Sort by Keys

This task is performed using sorted(), in this, we extract the keys using 1st index of items of dictionary extracted by items(), and pass it in key as custom lambda function to get sorted by keys. The “reverse=True” is added to perform reverse sort.

Python3




# Python3 code to demonstrate working of
# Sort a Dictionary
# Sort by Keys
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using items() to get all items
# lambda function is passed in key to perform sort by key
res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0])}
 
# printing result
print("Result dictionary sorted by keys : " + str(res))
 
# using items() to get all items
# lambda function is passed in key to perform sort by key
# adding "reversed = True" for reversed order
res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[0], reverse = True)}
 
# printing result
print("Result dictionary sorted by keys ( in reversed order ) : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Result dictionary sorted by keys : {'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7}
Result dictionary sorted by keys ( in reversed order ) : {'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2}

Case 2 : Sort by Values 

This task can be performed in similar way as above, the only difference being for extracting values, 2nd element of items() is passed as comparator. 

Python3




# Python3 code to demonstrate working of
# Sort a Dictionary
# Sort by Values
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using items() to get all items
# lambda function is passed in key to perform sort by key
# passing 2nd element of items()
res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1])}
 
# printing result
print("Result dictionary sorted by values : " + str(res))
 
# using items() to get all items
# lambda function is passed in key to perform sort by key
# passing 2nd element of items()
# adding "reversed = True" for reversed order
res = {key: val for key, val in sorted(test_dict.items(), key = lambda ele: ele[1], reverse = True)}
 
# printing result
print("Result dictionary sorted by values ( in reversed order ) : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Result dictionary sorted by values : {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}
Result dictionary sorted by values ( in reversed order ) : {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}

Method#3:Using collections.OrderedDict() and sorted() 

Approach

this approach uses the sorted() function to sort a dictionary by its values in either ascending or descending order. The sorted() function is called with the items() method of the dictionary and a key function that returns the second element of each tuple (i.e., the values) or their negation. The resulting list of tuples is passed to the OrderedDict() constructor to create a new ordered dictionary with the same key-value pairs as the original dictionary but sorted by value.

Algorithm

1. Call the sorted() function on the dictionary ‘test_dict’, passing a lambda function as the ‘key’ argument.
2. The lambda function takes each key-value pair as input and returns the key or value to sort by, depending on the desired order.
3. Use the sorted() function to return a list of sorted key-value pairs.
4. Pass the sorted list to the OrderedDict() constructor to create a new ordered dictionary.
5. Return the ordered dictionary.

Python3




from collections import OrderedDict
from operator import itemgetter
 
def sort_dict_by_value(test_dict):
    sorted_list = sorted(test_dict.items(), key=itemgetter(1))
    return OrderedDict(sorted_list)
 
def sort_dict_by_value_reverse(test_dict):
    sorted_list = sorted(test_dict.items(), key=itemgetter(1), reverse=True)
    return OrderedDict(sorted_list)
 
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
print(sort_dict_by_value(test_dict))
print(sort_dict_by_value_reverse(test_dict))


Output

OrderedDict([('Best', 2), ('Gfg', 5), ('is', 7), ('geeks', 8), ('for', 9)])
OrderedDict([('for', 9), ('geeks', 8), ('is', 7), ('Gfg', 5), ('Best', 2)])

Time Complexity: O(N log N), where N is the number of key-value pairs in the dictionary.
Space Complexity: O(N), as we are creating a new ordered dictionary to store the sorted key-value pairs.

Method 4 :  use the sorted() method with a lambda function as the key parameter. 

Here are the steps:

  1. Define the dictionary to be sorted.
  2. Use the sorted() method to sort the dictionary by values.
  3. Pass a lambda function as the key parameter to the sorted() method to specify that the sorting should be done by values.
  4. Use the dict() constructor to create a new dictionary from the sorted list of tuples.

Python3




def sort_dict_by_value_lambda(test_dict):
    sorted_list = sorted(test_dict.items(), key=lambda x: x[1])
    return dict(sorted_list)
 
def sort_dict_by_value_lambda_reverse(test_dict):
    sorted_list = sorted(test_dict.items(), key=lambda x: x[1], reverse=True)
    return dict(sorted_list)
 
test_dict = {"Gfg" : 5, "is" : 7, "Best" : 2, "for" : 9, "geeks" : 8}
print(sort_dict_by_value_lambda(test_dict))
print(sort_dict_by_value_lambda_reverse(test_dict))


Output

{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}
{'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}

Time complexity: O(n log n) where n is the number of items in the dictionary.

Auxiliary space: O(n) to store the sorted list of tuples. The dict() constructor takes O(n) time to create a new dictionary from the sorted list.



Similar Reads

Sort a Dictionary Without Using Sort Function in Python
As we all know Dictionaries in Python are unordered by default, which means they can’t be sorted directly. However, we can sort the keys or values of a dictionary and create a new sorted dictionary from the sorted keys or values. We can sort a list in a Dictionary using the inbuilt dictionary sort() function. But in this article, we will learn how
3 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 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
Practice Tags :