Open In App

Python – Synchronized Sorting of Keys

Last Updated : 24 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Dictionaries, we can have a problem in which we need to perform the sort of one key of dictionary and which to perform similar changes to corresponding keys as well. This kind has application in web development and competitive programming. Let’s discuss certain way in which this task can be performed.

Input : test_dict = {“Gfg” : [3, 2, 1], ‘best’ : [17, 10, 20]}, sort_key = “Gfg” Output : {‘Gfg’: [1, 2, 3], ‘best’: [20, 10, 17]} Input : test_dict = {“Gfg” : [3, 1], ‘best’ : [10, 20], ‘CS’ : [12, 43]}, sort_key = “Gfg” Output : {‘Gfg’: [1, 3], ‘best’: [20, 10], ‘CS’: [43, 12]}

Using dictionary comprehension + sorted() + list comprehension

The combination of above functionalities can be used to solve this problem. In this, we perform the sorting using sorted() and replication to other dictionaries is done using dictionary comprehension. 

Python3




# Python3 code to demonstrate working of
# Synchronized Sorting
# Using dictionary comprehension + sorted() + list comprehension
 
# initializing dictionary
test_dict = {"Gfg" : [4, 6, 7, 3, 10],
            'is' : [7, 5, 9, 10, 11],
            'best' : [1, 2, 10, 21, 12]}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# initializing sort key
sort_key = "Gfg"
 
# Synchronized Sorting
# Using dictionary comprehension + sorted() + list comprehension
temp = [ele for ele, idx in sorted(enumerate(test_dict[sort_key]),
                                        key = lambda x : x[1])]
 
res = {key : [val[idx] for idx in temp] for key, val in test_dict.items()}
     
# printing result
print("The Synchronized sorted dictionary : " + str(res))


Output

The original dictionary : {'Gfg': [4, 6, 7, 3, 10], 'is': [7, 5, 9, 10, 11], 'best': [1, 2, 10, 21, 12]}
The Synchronized sorted dictionary : {'Gfg': [3, 4, 6, 7, 10], 'is': [10, 7, 5, 9, 11], 'best': [21, 1, 2, 10, 12]}

Using itemgetter

This approach uses a dictionary comprehension to iterate over the key-value pairs in test_dict. For each key-value pair, it sorts the values based on the corresponding elements in the sort_key list. It achieves this by using the zip() function to combine the values from test_dict[sort_key] and v into tuples, and then sorting them based on the first element of each tuple. The sorted values are collected in a list comprehension.

Algorithm

1. Iterate over the key-value pairs in test_dict.
2. For each key-value pair, use the zip() function to combine the values from test_dict[sort_key] and v into tuples.
3. Sort the tuples based on the first element using the itemgetter(0) function.
4. Collect the sorted values in a list comprehension.
5. Assign the sorted values to the corresponding key in the sorted_dict dictionary.

Python3




from operator import itemgetter
 
test_dict = {"Gfg": [3, 2, 1], "best": [17, 10, 20]}
sort_key = "Gfg"
 
sorted_dict = {k: [x for _, x in sorted(zip(test_dict[sort_key], v), key=itemgetter(0)) ] for k, v in test_dict.items()}
print(sorted_dict)


Output

{'Gfg': [1, 2, 3], 'best': [20, 10, 17]}

Time Complexity: O(n * m * log m), where n is the number of key-value pairs in test_dict and m is the maximum length of the lists associated with each key. This is because the code performs a sorting operation on each list, which has a complexity of O(m * log m), and it iterates over n key-value pairs.

Space Complexity: O(n * m) because it creates a new dictionary sorted_dict with n key-value pairs, and the maximum size of each value list is m. Additionally, the code uses temporary space to store the sorted tuples during the sorting process.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads