11.4. Dictionaries and Tuples

Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair. (Technically, it returns a “view object,” but using it as the parameter in Python’s list() constructor converts it into a list.)

As you should expect from a dictionary, the items are in no particular order. However, since a list of tuples is a list, and tuples are comparable, we can sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key:

(If you need a reminder, the sort method sorts a list in alphabetical order.)

The resulting list is sorted in ascending alphabetical order by the key value.

The sort method also has an optional parameter, reverse, whose value can tell sort to sort in descending order.

Write code that will transform dictionary d into a list of tuples, called tup_list, sorted by the keys’ values in descending order.

You have attempted of activities on this page