Python Programming · Week 9

Dictionaries and Sets
In class

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Today

Three things

  1. 1 Recap and quiz: the week 9 videos
  2. 2 Exercise 7: all three problems, solved live
  3. 3 Next week: modules and packages
Recap · 1

A dictionary

>>>book = {"Kim": 85, "Lee": 72, "Park": 93}

>>>book

{'Kim': 85, 'Lee': 72, 'Park': 93}

>>>len(book)

33 pairs

>>>{}

{}an empty dictionary

key value "Kim"→85"Lee"→72"Park"→93
{ }curly braces key: valuea pair ,between pairs

a dictionary: key-value pairs · each key leads to its value

Recap · 2

Find a value by its key

a dictionary · by key

>>>book = {"Kim": 85, "Lee": 72, "Park": 93}

>>>book["Park"]

93

>>>book["Kang"]

KeyError: 'Kang'

"Kim"→85"Lee"→72"Park"→93

a list · week 7 · by position

>>>scores = [85, 72, 93, 60]

>>>scores[2]

93

index 0123 85729360
[key] gives its value a missing key: KeyError
Recap · 3

Add and change

>>>book = {}

{}

an empty dictionary

>>>book["Kim"] = 85

"Kim"85

a new key: added

>>>book["Lee"] = 72

"Kim"85"Lee"72

added at the end

>>>book["Kim"] = 90

"Kim"90"Lee"72

a key already there: changed

>>>{"Kim": 85, "Kim": 90}

{'Kim': 90}one key, one value

a key appears only once · the last value stays

Recap · 4

Is the key there?

>>>book = {"Kim": 85, "Lee": 72, "Park": 93}

>>>"Park" in book

True

>>>"Kang" in book

False

>>>85 in book

False

in looks at the keys

book[key] book.get(key) book.get(key, 0) "Park"there 93 93 93 "Kang"missing KeyError: 'Kang' Noneno error 0default

in: is the key there? · get: no KeyError, None or a default

Recap · 5

for over a dictionary

book = {"Kim": 85, "Lee": 72, "Park": 93}

book → "Kim""Lee""Park" the keys, in order

for name in book:name = "Kim"name = "Lee"name = "Park"

print(f"{name}: {book[name]}")

Kim: 85

Lee: 72

Park: 93

no more keys: the loop ends

for over a dictionary takes the keys · book[name]: its value

Recap · 6

keys() and values()

book = {"Kim": 85, "Lee": 72, "Park": 93}

for name in book.keys():

print(name)

Kim

Lee

Park

the same as for name in book:

for score in book.values():

print(score)

85

72

93

only the values

>>>sum(book.values())

250

>>>max(book.values())

93

keys(): only the keys · values(): only the values

Recap · 7

items(): key and value

book = {"Kim": 85, "Lee": 72, "Park": 93}

book.items() → ('Kim', 85)('Lee', 72)('Park', 93) (key, value) tuples

for name, score in book.items():name, score = ('Kim', 85)name, score = ('Lee', 72)name, score = ('Park', 93)

print(f"{name}: {score}")

Kim: 85

Lee: 72

Park: 93

items(): each key with its value · unpacked in the for line

Recap · 8

Two lists into a dictionary

>>>names = ["Kim", "Lee", "Park", "Choi"]

>>>scores = [85, 72, 93, 60]

>>>dict(zip(names, scores))

{'Kim': 85, 'Lee': 72, 'Park': 93, 'Choi': 60}

('Kim', 85)

('Lee', 72)

('Park', 93)

('Choi', 60)

key value "Kim"→85"Lee"→72"Park"→93"Choi"→60

each pair becomes a key and its value · dict(zip(keys, values))

Recap · 9

Nested data

a list of dictionaries · a position, then a key

>>>students = [{"name": "Kim", "score": 85},

... {"name": "Lee", "score": 72}]

>>>students[1]["score"]

72

students[1]["score"] first students[1]

↓

{'name': 'Lee', 'score': 72}["score"] then ["score"]: 72

a dictionary of lists · a key, then a position

>>>marks = {"Kim": [85, 90], "Lee": [72, 65]}

>>>marks["Kim"][1]

90

marks["Kim"][1] first marks["Kim"]

↓

[85, 90][1] then [1]: 90

from the outside in · one step at a time

Recap · 10

A set

>>>{3, 1, 3, 2}

{1, 2, 3}braces, no colons

>>>len(set([85, 72, 85, 93]))

3different scores

>>>sorted(set("banana"))

['a', 'b', 'n']each letter once

>>>set()

set()an empty set

>>>{}

{}an empty dictionary

1 2 3 3 duplicate: kept once

set

a set: no duplicates · no positions

Recap · 11

in, union, intersection

>>>a = {1, 2, 3, 5}

>>>b = {2, 3, 4}

>>>4 in b

True

>>>a | b

{1, 2, 3, 4, 5}

>>>a & b

{2, 3}

union intersection
a b 1 5 2 3 4

a | b: in either set · a & b: in both

Recap · 12

A list from a for loop

scores = [85, 72, 93, 60]

a loop · week 7

one line

bonus = []

for s in scores:

bonus.append(s + 5)

>>>[s + 5 for s in scores]

[90, 77, 98, 65]

list comprehension read: s + 5, for each s in scores

high = []

for s in scores:

if s >= 80:

high.append(s)

>>>[s for s in scores if s >= 80]

[85, 93]

if at the end: only the ones that pass

read it as a loop · the value, then the for, then the if

Quiz

What comes out?

No computer. Say what comes out, then I run it.

1

>>>teams = {"red": ["Kim", "Lee"], "blue": ["Park"]}

>>>len(teams)

>>>teams["red"][-1]

2

>>>dict(zip("abc", [1, 2, 3]))

3

>>>{1, 2, 3} & {4, 5}

>>>type({})

4

>>>[ch for ch in "hello" if ch != "l"]

5

quiz5.py

cart = {"apple": 2, "pear": 3}

total = 0

for x in cart:

total += x

print(total)

6

quiz6.py

prices = {"tea": 3, "cake": 5}

total = 0

for item in ["tea", "juice", "cake"]:

total += prices.get(item, 0)

print(total)

Exercise 7 · Problem 1

Both days

week09_problem1.py 2 points

A club event ran for two days. Ask for the names of the students who came on day 1, on one line, then on day 2. Print who came on both days, in alphabetical order, and how many different students came. A name typed twice on the same day is still one student.

on the screen · one run

Day 1: Kim Lee Park

Day 2: Park Choi Kim

Both days: ['Kim', 'Park']

Students: 4

the names after the prompts are typed · the prompt words are up to you

examples · typed values in order

typed

prints

Kim Lee Park / Park Choi Kim

Both days: ['Kim', 'Park'], Students: 4

Kim Lee / Park Choi

Both days: [], Students: 4

Kim Kim Lee / Kim

Both days: ['Kim'], Students: 2

Lee / Lee

Both days: ['Lee'], Students: 1

Exercise 7 · Problem 2

Class vote

week09_problem2.py 3 points

The class votes for its president. Ask for one name per vote, until an empty line. Print each candidate's votes, in the order of their first vote, then the winner. If two candidates have the most votes, the one who got a vote first wins.

on the screen · one run

Vote: Kim

Vote: Lee

Vote: Kim

Vote: Park

Vote: Kim

Vote: Lee

Vote:

Kim: 3

Lee: 2

Park: 1

Winner: Kim

the names after the prompts are typed; the last line is left empty

Hint: count the votes in a dictionary, as the word counter counts words; max of the dictionary's values is the most votes.

examples · typed values in order

typed

prints

Kim / Lee / Kim / Park / Kim / Lee

Kim: 3, Lee: 2, Park: 1, Winner: Kim

Lee / Kim / Kim / Lee

Lee: 2, Kim: 2, Winner: Lee

Park

Park: 1, Winner: Park

Exercise 7 · Problem 3

Club members

week09_problem3.py 5 points

Each student joins a club. Ask for lines of a name and a club, with a space between them, until an empty line. Print each club with the list of its members: the clubs in the order they first come, the members in the order they were typed.

on the screen · one run

Name and club: Kim chess

Name and club: Lee band

Name and club: Park chess

Name and club: Choi soccer

Name and club: Kang band

Name and club:

chess: ['Kim', 'Park']

band: ['Lee', 'Kang']

soccer: ['Choi']

the lines after the prompts are typed; the last one is left empty

steps, in words

  1. 1 Start with an empty dictionary.
  2. 2 For each line, take the name and the club. If the club is already a key, add the name to its list; if not, the club gets a new list holding the name.
  3. 3 Print each club with its list.

examples · typed values in order

typed

prints

the five lines in the run

chess: ['Kim', 'Park'], then band, soccer

Kim chess / Lee chess

chess: ['Kim', 'Lee']

Kim chess / Kim band

chess: ['Kim'], band: ['Kim']

Choi soccer

soccer: ['Choi']

Next week

Week 10: Modules and Packages

Exercise 7: due tomorrow, Tuesday, November 3, 11:59 a.m.
Week 10 videos and exercise 8: up Tuesday–Wednesday, November 3–4.
Exercise 8: due Monday, November 9, 11:59 a.m.

Slides: hyeongminlee.github.io/slides/python-programming

← All weeks
01 / 00
Scroll · ↓ · Space