Open In App

Python | Sort dictionary keys to list

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 sum() + sorted() + items() + lambda The combination of above functions can be used to perform this particular task. In this, firstly we sort the dictionary by keys for desired order using sorted(), then keys and values are extracted by items() functions that are returned as pair by lambda function. The sum function does the task of populating the tuple. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
# Using sum() + sorted() + items() + lambda
 
# initializing dictionary
test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using sum() + sorted() + items() + lambda
# Sort dictionary keys to list
res = list(sum(sorted(test_dict.items(), key = lambda x:x[1]), ()))
 
# printing result
print("List after conversion from dictionary : " + str(res))


Time Complexity: O(n*log n)

Space Complexity: O(n)

Output : 

The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3}
List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

  Method #2 : Using chain() + sorted() + items() + lambda This method is also similar to above method, the only difference is that the construction of the final list is done by the chain method which reduces the intermediate step of conversion to tuple and does the whole task in linear time. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
# Using chain() + sorted() + items() + lambda
from itertools import chain
 
# initializing dictionary
test_dict = {'Geeks' : 2, 'for' : 1, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using chain() + sorted() + items() + lambda
# Sort dictionary keys to list
res = list(chain(*sorted(test_dict.items(), key = lambda x: x[1])))
 
# printing result
print("List after conversion from dictionary : " + str(res))


Time Complexity: O(n*log n)

Space Complexity: O(n)

Output : 

The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3}
List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

Method #3 : Using keys(),values(),sort(),index() methods

Approach

  1. Extract keys, values using keys() and values() methods
  2. Sort the values list
  3. Append the keys and sorted values accordingly to output list
  4. Display output list

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
 
# initializing dictionary
test_dict = {'Geeks': 2, 'for': 1, 'CS': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = []
x = list(test_dict.keys())
y = list(test_dict.values())
z = []
z.extend(y)
z.sort()
for i in z:
    res.append(x[y.index(i)])
    res.append(i)
# printing result
print("List after conversion from dictionary : " + str(res))


Output

The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3}
List after conversion from dictionary : ['for', 1, 'Geeks', 2, 'CS', 3]

Time Complexity : O(N logN)

Auxiliary Space : O(N)

Method #5: Using map(), zip() and sorted()

Use the zip() function to create a list of tuples, where each tuple contains a key-value pair from the dictionary.
Use the map() function to create a list of tuples, where each tuple contains a key and its corresponding value.
Use the sorted() function to sort the list of tuples by the keys.
Use the zip() function again to create a list of tuples, where each tuple contains a key and its corresponding value.
Use a list comprehension to flatten the list of tuples into a single list.
Return the flattened list.

Python3




# Python3 code to demonstrate working of
# Sort dictionary keys to list
 
# initializing dictionary
test_dict = {'Geeks': 2, 'for': 1, 'CS': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# sorting dictionary keys to list using map(), zip() and sorted()
res = [elem for tup in sorted(zip(test_dict.keys(), test_dict.values())) for elem in tup]
 
# printing result
print("List after conversion from dictionary : " + str(res))


Output

The original dictionary is : {'Geeks': 2, 'for': 1, 'CS': 3}
List after conversion from dictionary : ['CS', 3, 'Geeks', 2, 'for', 1]

Time complexity: O(n log n) for sorting the keys and O(n) for iterating over the dictionary and creating the list of tuples, so overall O(n log n).

Auxiliary space: O(n) for the res list



Last Updated : 05 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads