![]() |
VOOZH | about |
We are given a dictionary where the values are strings and our task is to retrieve the items in sorted order based on the values. For example, if we have a dictionary like this: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} then the output will be ['akshat', 'bhuvan', 'chandan']
sorted() function can be used to sort the values of a dictionary and we can retrieve the dictionary values using values().
['akshat', 'bhuvan', 'chandan']
Explanation:
Instead of sorting the values directly we can also sort the dictionary items (key-value pairs) and extract the values in sorted order using a lambda function.
['akshat', 'bhuvan', 'chandan']
Explanation:
operator module provides the itemgetter() function which can be used to extract a specific item from a tuple or list. In this case we can use itemgetter(1) to sort by the second element (the value) in the dictionary’s items.
['akshat', 'bhuvan', 'chandan']
Explanation:
OrderedDict class from the collections module maintains the order of the item and we can use this to create a sorted dictionary and then extract the values in sorted order.
['akshat', 'bhuvan', 'chandan']
Explanation: OrderedDict(sorted(d.items(), key=lambda x: x[1])) sorts the dictionary items by value and creates an ordered dictionary with the sorted items and then we extract the values using values().