sorted() can be used to sort the following:
(a) keys in a dictionary
(b) dictionary according to the values
(c) lists
(d) All of these.
Answer:
The sorted() function is used to return a sorted list of the items in an iterable object in Python.
The sorted() function can be used to sort the following types of objects:
- Keys in a dictionary: The sorted() function can take a dictionary object as an argument and return a sorted list of the keys. For example, if mydict = {‘a’: 23, ‘b’: ‘78’, ‘d’: 36}, then sorted(mydict) will return [‘a’, ‘b’, ‘d’], which is a sorted list of the keys in the dictionary.
- Dictionary according to the values: The sorted() function can also take a dictionary object as an argument and return a sorted list of the key-value pairs according to the values. For example, if mydict = {‘a’: 23, ‘b’: ‘78’, ‘d’: 36}, then sorted(mydict, key=mydict.get) will return [‘a’, ‘d’, ‘b’], which is a sorted list of the key-value pairs according to the values in ascending order.
- Lists: The sorted() function can take a list object as an argument and return a sorted list of the items. For example, if mylist = [5, 2, 9, 7, 1], then sorted(mylist) will return [1, 2, 5, 7, 9], which is a sorted list of the items in ascending order.
Therefore , all of these types of objects can be sorted using the sorted() function in Python.
So, the correct answer is (d) All of these.