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.)

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

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 in descending order.

You have attempted 1 of 7 activities on this page