Python - Sort Dictionary by Values and Keys
Last Updated :
11 Apr, 2023
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically.
Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexicographically sorted keys. Input : test_dict = {"gfg" : 5, "is" : 4, "best" : 3, "for" : 2, "geeks" : 1} Output : {"gfg" : 5, "is" : 4, "best" : 3, "for" : 2, "geeks" : 1} Explanation : All values are different, hence descending ordered sorted.
Method : Using sorted() + items() + dictionary comprehension + lambda
The combination of above functions can be used to solve this problem. In this, we perform task of sorting using sorted(), dictionary comprehension is used to remake dictionary, items() is used to extract items to sorted.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by Values and Keys
# Using sorted() + items() + dictionary comprehension + lambda
# initializing dictionary
test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2, "for" : 3, "Geeks" : 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# - sign for descended values, omit if low-high sorting required
res = {val[0] : val[1] for val in sorted(test_dict.items(), key = lambda x: (-x[1], x[0]))}
# printing result
print("Sorted dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2, 'for': 3, 'Geeks': 2}
Sorted dictionary : {'for': 3, 'is': 3, 'Best': 2, 'Geeks': 2, 'Gfg': 1}
Time Complexity: O(n*nlogn)
Auxiliary Space: O(n)
Method 2: Using operator.itemgetter() and sorted()
- Import the itemgetter() function from the operator module.
- Initialize the input dictionary test_dict.
- Use the sorted() function to sort the dictionary based on the keys and values, bypassing the itemgetter() function as a key.
- Assign the sorted dictionary to the res variable.
- Print the original and sorted dictionaries.
Python3
# importing itemgetter function
from operator import itemgetter
# initializing dictionary
test_dict = {"Gfg": 1, "is": 3, "Best": 2, "for": 3, "Geeks": 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting dictionary by keys and values
res = dict(sorted(test_dict.items(), key=itemgetter(0, 1)))
# printing result
print("Sorted dictionary : " + str(res))
OutputThe original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2, 'for': 3, 'Geeks': 2}
Sorted dictionary : {'Best': 2, 'Geeks': 2, 'Gfg': 1, 'for': 3, 'is': 3}
Time Complexity: The time complexity of this method is O(n log n), where n is the number of items in the dictionary. This is because we are using the sorted() function, which has a time complexity of O(n log n).
Auxiliary Space: The auxiliary space used by this method is O(n), where n is the number of items in the dictionary. This is because we are creating a new dictionary res with the same number of items as the input dictionary test_dict.
Similar Reads
Python - Sort Dictionary key and values List Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read
Python - Sort List by Dictionary values Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
3 min read
Sort Python Dictionary by Value Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
3 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python - Sort Dictionary by key-value Summation Given a Dictionary, sort by summation of key and value. Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1} Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6} Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values. Input : test_dict = {3:5, 1:3, 4:6, 2:7} Output : {1: 3, 3: 5, 2: 7, 4:
5 min read