Dictionary is a collection in python which is used to store data as Key:value pair.
Example:
dict = { "python" : 1, "C++" : 3, "javaScript" : 2 }
Sort a Dictionary key and values list
We are given a dictionary with key-value pairs in an unsorted manner where values are an unordered list. We need to create a program that will sort the keys of the dictionary i.e. make it an ordered one and also sort the value list of the dictionary.
Input:
dict = {'john' : [70, 82, 55], 'ram' : [92, 99, 98], 'jane' : [65, 34, 76]}
Output:
dict = { 'jane' : [34, 34, 76], 'john' : [55, 70, 82], 'ram' : [92, 98, 99]}
In the Python programming language, we can sort any collection using the sorted method. We need to first sort the dictionary and then sort the value list for each key in the dictionary. A simple solution for this is using the sorted function and then for each of the key's values again use the sorted function. And store these sorted values in a new dictionary.
Program 1: Sort a dictionary key and values list
Output:
Python also provides the function to perform the above task in a single line of code using dictionary comprehension which is a single line of code which replaces the logic for sorting with a single line of code which will perform the same task. Here, is the line of code to be added to our program,
If you observe it closely it's the same code but in a single line and a neat way (these are good coding practices you should learn).
Program 2: Sort a dictionary key and values list
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer