Comp 112

Lecture 10

Tuples and Dictionaries

2018.04.03

Tuples

Tuples vs Lists

Tuple Indexing and Slicing

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

Returning Multiple Values

Tuple Assignment

Enumerating a List

Sometimes we want to iterate over a list without controlling the order, but we still want access to the indices:

There is a built-in function called enumerate with signature any a . iterator a -> iterator (tuple (int , a)) that packages up each list entry with its index:

Letting us write:

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

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

Recall that there is a function called sorted that returns a sorted (according to “_<=_”) version of a list (or iterator):

To sort our olympic records chronologically:

or:

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

To Do This Week: