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.)
- True
- Incorrect! Look closely at the second line. Notice anything missing? Try again.
- False
- Correct! Parentheses are required when calling the items() method.
11-9-2: True or false? The following code will correctly output the items of the dictionary t.
name_dictionary = {'Bob': 5, 'Melissa': 3, 'John': 7, 'Kim': 5}
t = list(name_dictionary.items)
print(t)
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.
- In ascending order by the keys' first letter.
- Correct! This is the way that the sort() method sorts lists of tuples.
- In descending order by each key's value.
- Incorrect! The sort() method doesn't consider the keys' values at all. Try again.
- In descending order by the keys' first letter.
- Incorrect! The default way that the sort() method sorts is in ascending order. Try again.
- In ascending order by each key's value.
- Incorrect! The sort() method doesn't consider the keys' values at all. Try again.
11-9-4: How will the list below be sorted (if there is any order at all)?
grocery_dict = {'apple': 5, 'pineapple': 3, 'chicken': 8, 'kiwi': 7}
grocery_list = list(grocery_dict.items())
grocery_list.sort()
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.