Comp 112

Lecture 9

Tuples and Dictionaries

2017.10.31

Tuples

Tuples vs Lists

Tuple Indexing and Slicing

john = ("Lennon" , "John" , 1940)  #  signature: tuple (str , str , int)

Returning Multiple Values

Tuple Assignment

Example: Spreadsheets

Dictionaries

Lists as Lookup Tables

One way to think of a list:

is as a look-up table:

index value
0 "John"
1 "Paul"
2 "George"
3 "Ringo"

From this perspective, the table’s look-up indices are the numbers from 0 to len (xs) - 1.

But there is no reason why a table’s look-up indices need to be these particular numbers.

Olympic men’s 100m winners:

index value
0 "N/A"
1 "N/A"
1895 "N/A"
1896 "Thomas Burke"
1897 "N/A"
1898 "N/A"
1899 "N/A"
1900 "Frank Jarvis"
1901 "N/A"
2015 "N/A"
2016 "Usain Bolt"

…or even numbers at all.

Dictionaries

olympic_mens_100 = dict ()                # signature: dict (int -> str)
olympic_mens_100 [1896] = 'Thomas Burke'  # ...
olympic_mens_100 [1988] = 'Ben Johnson'
del olympic_mens_100 [1988]               # revoked due to doping
olympic_mens_100 [1988] = 'Carl Lewis'    # ...
olympic_mens_100 [2012] = 'Usain Bolt'
olympic_mens_100 [2016] = 'Usain Bolt'

Our signatures for dictionaries include the signatures for the keys and values.

Dictionary Notation

Keys and Values

The objects returned by these methods are list-like iterators.

If you need an actual list then coerce them with the list function:

om100_key_list = list (olympic_mens_100.keys ())

Iterating Over a Dictionary

Key Sorting

Key Testing

Example: Letter Counting

def letter_counts (text) :
    # signature:  str -> dictionary (str -> int)
    counts = dict ()                     # initialize the dictionary
    for character in text.lower () :     # count the letter occurrences
        if str.isalpha (character) :
            if character not in counts :
                counts [character] = 0
            counts [character] += 1
    return counts
def print_counts (text) :
    # signature:  str -> NoneType
    # prints sorted letter frequencies
    tally = letter_counts (text)
    for (letter , count) in sorted (tally.items ()) :
        print (letter + ": " + str (count))
two_cities = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, \
it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, \
it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us..."

To Do This Week: