You have a dictionary of student names and their scores. How would you get a list of student names sorted by their scores in descending order?
- sorted_names = sorted(students.items(), key=lambda x: x[1])
- sorted_names = sorted(students.items(), key=lambda x: x[1], reverse=True)
- sorted_names = students.items().sort(key=lambda x: x[1])
- sorted_names = students.items().sort(key=lambda x: x[1], reverse=True)
The correct way to sort the dictionary by scores in descending order is to use the sorted() function with a lambda function as the key argument. The lambda function extracts the score (value) from each (key, value) pair and sorts the items accordingly.
Loading...
Related Quiz
- You are designing a framework and want to ensure that all classes following a certain API have required methods implemented. How would you use metaclasses to achieve this?
- You are building a recommendation engine and have a set of products bought by User A and another set for User B. To recommend new products to User A based on User B's purchases, which set operation would you use considering you don't want to recommend products User A has already bought?
- Packages in Python provide a way of organizing related modules into a single _______ directory hierarchy.
- How would you analyze the reference count of an object in Python to debug memory issues?
- A Python script unexpectedly terminates, and upon investigation, you discover a circular import. What could be a probable solution?