0% found this document useful (0 votes)
12 views12 pages

W08B Full

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Tuples and Nested Dictionaries

Introduction to Computer Programming


Lecture W08B

Prof. Rutwa Engineer,


Prof. Dan Zingaro,
Prof. Peter Dixon,
Prof. Randy Hickey,
Prof. Romina Piunno

Mathematical and Computational Sciences


University of Toronto Mississauga
1 / 12
Agenda

1. Introduction to Tuples

2. Nested Dictionary Example

3. Tasks

2 / 12
Definition 1 (Tuple)
A tuple is an ordered sequence of elements. An n-tuple is a tuple
with exactly n elements.
Round brackets () are used to create tuples in Python.

1 >>> xs = (1, 2)
2 >>> type(xs)
3 <class 'tuple'>

3 / 12
Tuples, like strings and unlike lists, are immutable. They can be
indexed and sliced.

1 >>> xs[0]
2 1
3 >>> xs[0] = 2
4 TypeError: 'tuple' object does not support item
5 assignment

4 / 12
Dictionary Warmup

Task 1

1 def invert(H: dict) -> dict[list]:


2 """Return a dictionary for doing reverse lookups on H.
3 >>> invert({1: 10, 2: 10, 3: 'A'})
4 {10: [1, 2], 'A': [3]}
5 """

Let’s solve this together. Do you remember ideas for how to


approach this?

5 / 12
Nesting Dictionaries

As with lists, dictionaries can be nested.

1 >>> book_series = {
2 ... 'Animorphs':
3 ... {'author': 'K.A. Applegate', 'number': 54, 'genre': 'middle grade'},
4 ... 'Inheritance Games':
5 ... {'author': 'Jennifer Lynn Barnes', 'number': 2, 'genre': 'adult'},
6 ... 'Shopaholic':
7 ... {'author': 'Sophie Kinsella', 'number': 10, 'genre': 'adult'}
8 ... }
9 >>> book_series['Animorphs']['author']
10 'K.A. Applegate'

6 / 12
1 >>> for series in book_series:
2 ... for detail in book_series[series]:
3 ... print(detail, book_series[series][detail])
4 author K.A. Applegate
5 number 54
6 genre middle grade
7 author' Jennifer Lynn Barnes
8 number 2
9 genre adult
10 author Sophie Kinsella
11 number 10
12 genre adult

7 / 12
Task 2
1 def find_books(book_series: dict[str, dict], genre: str) -> list[str]:
2 """Return a list of all book series in genre.
3 >>> find_books(book_series, 'adult')
4 ['Inheritance Games', 'Shopaholic']
5 """

Challenge: return a list of lists consisting of the number of books


with their authors.

1 >>> find_books(book_series, 'adult')


2 [[2, 'Jennifer Lynn Barnes'], [10, 'Sophie Kinsella']]

8 / 12
9 / 12
Trie as Dictionary

trie = {
't': {
'h': {
'a': {'t': {}},
'e': {'r': {'e':{}}},
'i': {'s': {}}
}
},
'd': ...
}

10 / 12
Task 3
The code in trie.py will generate tries for you. Then implement:

1 def in_trie(word: str, trie: dict[str, dict]) -> bool:


2 """Return True only when word is found in trie.
3 >>> in_trie('that', trie)
4 True
5 >>> in_trie('paul', trie)
6 False
7 """

11 / 12
Next Time

1. Lazy Literature (random text generation!)

12 / 12

You might also like