Open In App

Python – Sort Dictionary key and values List

Last Updated : 27 Jul, 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 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




# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
 
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
             'is': [2, 10, 3],
             'best': [19, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
    res[key] = sorted(test_dict[key])
 
# printing result
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




# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
 
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
             'is': [2, 10, 3],
             'best': [19, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
res = {key : sorted(test_dict[key]) for key in sorted(test_dict)}
 
# printing result
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




# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using lambda function with sorted()
 
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
             'is': [2, 10, 3],
             'best': [19, 4]}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Sort Dictionary key and values List
# Using lambda function with sorted()
res = dict(sorted(test_dict.items(), key=lambda x: x[0]))
 
for key in res:
    res[key] = sorted(res[key])
 
# printing result
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




# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using zip() function with sorted()
 
# initializing dictionary
test_dict = {'gfg': [7, 6, 3],
             'is': [2, 10, 3],
             'best': [19, 4]}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Sort Dictionary key and values List
# Using zip() function with sorted()
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}
 
# printing result
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:

  1. Base Case: If the input dictionary is empty, return an empty dictionary.
  2. Recursive Case: Find the key with the minimum value list length in the input dictionary. Call it min_key.
  3. Sort the value list associated with min_key.
  4. Remove min_key from the input dictionary and call the resulting dictionary rest_dict.
  5. Recursively call sort_dict_recursive on rest_dict and call the resulting dictionary sorted_rest_dict.
  6. 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 - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python | Filter dictionary key based on the values in selective list
In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is quite common in web development we require to get only the selective dictionary keys from some given list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension The list comprehension can be used to solv
9 min read
Python - Convert key-values list to flat dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed. Convert key-values list to flat dictionary usin
4 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', 'for': 'Me'}] Explanation : Sort in order of e =
7 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 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
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 be performed. Sort Dictionary by Value in Python u
3 min read
Python - Extract target key from other key values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract particular key on basis of other matching record keys when there is exact match. Lets discuss certain ways in which this task can be performed. Method #1: Using loop + conditions This is one of the ways in which this task can be performed. In this,
11 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
Practice Tags :