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 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.