Skip to main content
Contents Index
Search Book
Search Results:
No results.
Readability settings Prev Up Next Scratch ActiveCode Profile
title here
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 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.)
Activity 11.4.1 .
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.
Activity 11.4.2 .
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()
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.
The
sort method also has an optional parameter,
reverse, whose value can tell
sort to sort in descending order.
Activity 11.4.3 .
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
of
activities on this page.