Python – Sort Dictionary key and values List
Last Updated :
27 Jul, 2023
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_dict = {‘c’: [3], ‘b’: [12, 10], ‘a’: [19, 4]}
Output : {‘a’: [4, 19], ‘b’: [10, 12], ‘c’: [3]}
Input : test_dict = {‘c’: [10, 34, 3]}
Output : {‘c’: [3, 10, 34]}
Sort Dictionary key and values List Using sorted() + loop
The combination of above functions can be used to solve this problem. In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner.
Python3
test_dict = { 'gfg' : [ 7 , 6 , 3 ],
'is' : [ 2 , 10 , 3 ],
'best' : [ 19 , 4 ]}
print ("The original dictionary is : " + str (test_dict))
res = dict ()
for key in sorted (test_dict):
res[key] = sorted (test_dict[key])
print ("The sorted dictionary : " + str (res))
|
Output :
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]} The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Sort Dictionary key and values List Using dictionary comprehension + sorted()
The combination of above functions can be used to solve this problem. In this, we perform the task of dual sorting inside dictionary comprehension construct.
Python3
test_dict = { 'gfg' : [ 7 , 6 , 3 ],
'is' : [ 2 , 10 , 3 ],
'best' : [ 19 , 4 ]}
print ("The original dictionary is : " + str (test_dict))
res = {key : sorted (test_dict[key]) for key in sorted (test_dict)}
print ("The sorted dictionary : " + str (res))
|
Output :
The original dictionary is : {‘gfg’: [7, 6, 3], ‘is’: [2, 10, 3], ‘best’: [19, 4]} The sorted dictionary : {‘best’: [4, 19], ‘gfg’: [3, 6, 7], ‘is’: [2, 3, 10]}
Time complexity: O(n log n), where n is the total number of values in the input dictionary test_dict.
Auxiliary space: O(n), where n is the total number of values in the input dictionary test_dict.
Sort Dictionary key and values List Using lambda function with sorted()
Sorts a dictionary by its keys and also sorts the values for each key using the sorted() function with a lambda function as the key. initializes a dictionary with some key-value pairs, sorts it, and then prints both the original and sorted dictionaries.
Python3
test_dict = { 'gfg' : [ 7 , 6 , 3 ],
'is' : [ 2 , 10 , 3 ],
'best' : [ 19 , 4 ]}
print ( "The original dictionary is: " + str (test_dict))
res = dict ( sorted (test_dict.items(), key = lambda x: x[ 0 ]))
for key in res:
res[key] = sorted (res[key])
print ( "The sorted dictionary: " + str (res))
|
Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
The sorted dictionary: {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}
Time complexity: O(n log n), where n is the number of keys in the dictionary.
Auxiliary space: O(n), where n is the number of keys in the dictionary.
Sort Dictionary key and values List Using the zip() function with sorted() function.
Step-by-step approach:
- Initialize the dictionary.
- Get the list of keys and values separately.
- Use the zip() function to create a list of tuples, where each tuple contains a key and its corresponding value list.
- Sort the list of tuples using the sorted() function and a lambda function that sorts the tuples based on the first element of each tuple (i.e., the key).
- Use a dictionary comprehension to create a new dictionary from the sorted list of tuples.
- Print the sorted dictionary.
Below is the implementation of the above approach:
Python3
test_dict = { 'gfg' : [ 7 , 6 , 3 ],
'is' : [ 2 , 10 , 3 ],
'best' : [ 19 , 4 ]}
print ( "The original dictionary is: " + str (test_dict))
keys = list (test_dict.keys())
values = list (test_dict.values())
sorted_tuples = sorted ( zip (keys, values), key = lambda x: x[ 0 ])
res = {k: sorted (v) for k, v in sorted_tuples}
print ( "The sorted dictionary: " + str (res))
|
Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
The sorted dictionary: {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}
Time complexity: O(n log n) due to sorting, where n is the number of keys in the dictionary.
Auxiliary space: O(n) because we are using additional space to store the list of tuples.
Sort Dictionary key and values List Using Recursive method.
Algorithm:
- Base Case: If the input dictionary is empty, return an empty dictionary.
- Recursive Case: Find the key with the minimum value list length in the input dictionary. Call it min_key.
- Sort the value list associated with min_key.
- Remove min_key from the input dictionary and call the resulting dictionary rest_dict.
- Recursively call sort_dict_recursive on rest_dict and call the resulting dictionary sorted_rest_dict.
- Return a new dictionary with min_key as the key and the sorted value list as the value, merged with sorted_rest_dict.
Python3
def sort_dict_recursive(test_dict):
if not test_dict:
return {}
min_key = min (test_dict.keys())
sorted_values = sorted (test_dict[min_key])
rest_dict = {k: v for k, v in test_dict.items() if k ! = min_key}
sorted_rest_dict = sort_dict_recursive(rest_dict)
return {min_key: sorted_values, * * sorted_rest_dict}
test_dict = { 'gfg' : [ 7 , 6 , 3 ], 'is' : [ 2 , 10 , 3 ], 'best' : [ 19 , 4 ]}
res = sort_dict_recursive(test_dict)
print ( "The original dictionary is: " + str (test_dict))
print ( "The sorted dictionary : " + str (res))
|
Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
The sorted dictionary : {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}
Time Complexity: O(n log n) – The function makes n recursive calls, and each call sorts a list of length m, where m is the length of the smallest values list in the remaining dictionary. Sorting a list has a time complexity of O(m log m), so the overall time complexity is dominated by the sorting operations, which gives us O(n log n).
Auxiliary Space: O(n) – The recursive function creates a new dictionary and list for each recursive call, so the space complexity is proportional to the size of the input dictionary. In the worst case, where all values lists are of equal length, the size of the output dictionary is the same as the size of the input dictionary, so the space complexity is O(n).
Similar Reads
Python - Sort Dictionary by Values and Keys
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 lexico
3 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
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
2 min read
Python | Sort dictionary by value list length
While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
4 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Sorting Python Dictionary With Lists as Values
Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python. Sort a Dictionary with Lists as Values in Pyt
3 min read
Python - Sort Dictionary List by Key's ith Index value
Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Sort a List of Python Dictionaries by a Value
Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
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