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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

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