Sometimes, while working with Python dictionaries, we can have problem in which we need to perform sorting of dictionary elements. This is quite straight forward, but sometimes, we can have certain stray keys, which we don’t wish to alter order while sorting. This works for Python >= 3.6 as keys are ordered in dictionary this version onwards. This can have applications in data domains. Let’s discuss a way in which this task can be performed.
Input : test_dict = {“*-*” : “stray”, 70 : ‘is’} Output : {“*-*” : “stray”, 70 : ‘is’} Input : test_dict = {54 : “gfg”, “*-*” : “stray”, 20 : ‘best’} Output : {20: ‘best’, ‘*-*’: ‘stray’, 54: ‘gfg’}
Method : Using next() + sorted() + insert() The combination of above methods, can be used to solve this problem. In this, we perform sorting using sorted(), insert() is used to insert the stray element at its position and next() is used to get next key in order in case of initial stray key.
Python3
# Python3 code to demonstrate working of # Sort Dictionary ignoring Key # Using next() + sorted() + insert() # initializing dictionary test_dict = { 45 : 'is' , 12 : 'gfg' , 100 : 'best' , " * - * " : "stray", 150 : 'neveropen' , 120 : 'for' } # printing original dictionary print ("The original dictionary is : " + str (test_dict)) # strary key stray_key = '*-*' # Sort Dictionary ignoring Key # Using next() + sorted() + insert() temp = next (idx for idx, val in enumerate (test_dict) if val = = stray_key) idx = sorted (ele for ele in test_dict if ele ! = stray_key) idx.insert(temp, stray_key) res = {ele: test_dict[ele] for ele in idx} # printing result print ("The dictionary after sorting : " + str (res)) |
The original dictionary is : {45: ‘is’, 12: ‘gfg’, 100: ‘best’, ‘*-*’: ‘stray’, 150: ‘neveropen’, 120: ‘for’} The dictionary after sorting : {12: ‘gfg’, 45: ‘is’, 100: ‘best’, ‘*-*’: ‘stray’, 120: ‘for’, 150: ‘neveropen’}
Method#2 : Using lambda+dict
Approach
we use the built-in sorted() function to sort the dictionary by values. We ignore the keys by using a lambda function that returns only the values for comparison. The sorted() function returns a list of tuples, which we can convert back to a dictionary.
Algorithm
1. Create a lambda function that returns only the values from the dictionary.
2. Use the sorted() function with the dictionary and the lambda function as arguments to sort the dictionary by values.
3. Convert the sorted list of tuples back to a dictionary.
Python3
def sort_dict(test_dict): #define inputs sorted_dict = dict ( sorted (test_dict.items(), key = lambda x: x[ 1 ])) #sort dict using lambda return sorted_dict #return result test_dict = { 54 : 'gfg' , '*-*' : 'stray' , 20 : 'best' } #input print (sort_dict(test_dict)) #print result |
{20: 'best', 54: 'gfg', '*-*': 'stray'}
Time Complexity: O(nlogn) – sorting the dictionary takes nlogn time complexity.
Space Complexity: O(n) – creating a list of tuples for the sorted dictionary.
Method#3: using collections.OrderedDict:
1.Import the collections module.
2.Initialize the original dictionary test_dict with some key-value pairs.
3.Create a new dictionary sorted_dict using the collections.OrderedDict constructor and pass to it the sorted list of key-value pairs of the original dictionary based on their values. The sorted() function is used to sort the dictionary items based on the values using the key argument which 4.specifies a lambda function to extract the values of each item in the dictionary.
5.Print the original and sorted dictionaries.
Python3
import collections # initialize dictionary test_dict = { 45 : 'is' , 12 : 'gfg' , 100 : 'best' , "*-*" : "stray" , 150 : 'neveropen' , 120 : 'for' } # sort dictionary by values using OrderedDict sorted_dict = collections.OrderedDict( sorted (test_dict.items(), key = lambda x: x[ 1 ])) # print the original dictionary print ( "Original Dictionary:" ) print (test_dict) # print the sorted dictionary print ( "Sorted Dictionary:" ) print (sorted_dict) #This code is contributed by Jyothi pinjala |
Original Dictionary: {45: 'is', 12: 'gfg', 100: 'best', '*-*': 'stray', 150: 'neveropen', 120: 'for'} Sorted Dictionary: OrderedDict([(100, 'best'), (120, 'for'), (150, 'neveropen'), (12, 'gfg'), (45, 'is'), ('*-*', 'stray')])
The time complexity :O(nlogn), where n is the size of the original dictionary, because sorting the dictionary based on values using sorted() takes O(nlogn) time.
The auxiliary space : O(n) because we are creating a new dictionary with the same number of key-value pairs as the original dictionary.
Method#4: Using operator.itemgetter():
Algorithm:
1.Get the dictionary to be sorted.
2.Use the sorted() function to sort the dictionary by its values using operator.itemgetter() to retrieve the value of each item.
3.Convert the sorted result into a dictionary using the dict() constructor.
4.Iterate over the items in the sorted dictionary and print them in the desired format.
Python3
import operator test_dict = { 45 : 'is' , 12 : 'gfg' , 100 : 'best' , "*-*" : "stray" , 150 : 'neveropen' , 120 : 'for' } # print the original dictionary print ( "Original Dictionary:" ) print (test_dict) # sort the dictionary by values using operator.itemgetter() sorted_dict = dict ( sorted (test_dict.items(), key = operator.itemgetter( 1 ))) # print the sorted dictionary in the desired format for key, value in sorted_dict.items(): print (f "{key}: {value}" ) #This code is contributed by Vinay pinjala. |
Original Dictionary: {45: 'is', 12: 'gfg', 100: 'best', '*-*': 'stray', 150: 'neveropen', 120: 'for'} 100: best 120: for 150:neveropen 12: gfg 45: is *-*: stray
The time complexity :O(n log n), where n is the number of items in the dictionary. This is because the sorted() function used to sort the dictionary has a time complexity of O(n log n).
The Auxiliary space :O(n). This is because the algorithm creates a new list of dictionary items that is n items long to sort the dictionary. It then creates a new dictionary that is n items long to hold the sorted items. Finally, it iterates over the sorted dictionary and prints the items, which takes O(n) space in the worst case. Therefore, the space complexity of the algorithm is O(n).
Method #5: Using the items() method, sorted() method and dictionary comprehension
Algorithm:
- Define a function named “sort_dict” that takes “test_dict” as input.
- Sort the dictionary items using the sorted() method with a lambda function as the key.
- Create a new dictionary with sorted items and return the sorted dictionary.
Python3
def sort_dict(test_dict): sorted_items = sorted (test_dict.items(), key = lambda x: x[ 1 ]) sorted_dict = {key: value for key, value in sorted_items} return sorted_dict test_dict = { 54 : 'gfg' , '*-*' : 'stray' , 20 : 'best' } print (sort_dict(test_dict)) |
{20: 'best', 54: 'gfg', '*-*': 'stray'}
Time complexity: O(n log n) in the worst case where n is the size of the dictionary. Creating a new dictionary takes O(n) time. Therefore, the overall time complexity of the function is O(n log n).
Auxiliary Space: O(n) in the worst case where n is the size of the dictionary depending on the size of the input dictionary. The sorted_items list takes O(n) space, and the sorted dictionary takes O(n) space.