Python Programming · Week 9

Dictionaries and Sets
Practice

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Setup

Before we start

A new folder for this week.

  1. 1 VS Code → open your python_course folder
  2. 2 New Folder → week09
Files

scores.py

In your week09 folder: the program from the theory video.

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

scores = [85, 72, 93, 60]

book = dict(zip(names, scores))

for name, score in book.items():

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

print(f"Average: {sum(book.values()) / len(book)}")

while True:

name = input("Name: ")

if name == "":

break

print(book.get(name, "not found"))

Kim: 85

Lee: 72

Park: 93

Choi: 60

Average: 77.5

Name: Park

93

Name: Kang

not found

Name:

the last name: an empty line, Enter only

Drill

Break three things

In scores.py, on purpose. After each one, undo it: ⌘Z (Windows: Ctrl+Z).

the for line

drop .items(): for name, score in book:

ValueError: too many values to unpack (expected 2)

for takes the keys: "Kim" is one string, three letters

the Average line

drop .values(): sum(book)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

sum takes the keys too: it tries to add up the names

the last line

square brackets: print(book[name]) · type Kang

KeyError: 'Kang'

a missing key stops the program

for, sum: a dictionary gives its keys · a key that may be missing: get

Example · 1

Phone book

phone.py

A phone book that starts empty. Ask for a name, again and again, until an empty line. A new name: ask for its number, save it, and print Saved. A name already saved: print its number.

in: is the name a key yet? · phones[name] = number: a new pair, while the program runs

on the screen

Name: Kim

Number: 010-1234-5678

Saved.

Name: Lee

Number: 010-2345-6789

Saved.

Name: Kim

010-1234-5678

Name:

the code

phones = {}

while True:

name = input("Name: ")

if name == "":

break

if name in phones:

print(phones[name])

else:

number = input("Number: ")

phones[name] = number

print("Saved.")

Example · 2

Word counter

wordcount.py

Ask for a sentence. Print each word with how many times it comes, in the order the words first come. The and the are one word.

counts.get(word, 0) + 1: the first time, 0 + 1 · .lower(): The and the become one key

on the screen

Sentence: The cat and the dog and the bird

the: 3

cat: 1

and: 2

dog: 1

bird: 1

Sentence: Hello hello HELLO

hello: 3

the code

sentence = input("Sentence: ").lower()

counts = {}

for word in sentence.split():

counts[word] = counts.get(word, 0) + 1

for word, count in counts.items():

print(f"{word}: {count}")

Debugger

Watch the dictionary grow

1sentence = input("Sentence: ").lower()

2

3counts = {}

4for word in sentence.split():

5 counts[word] = counts.get(word, 0) + 1

⋮

word and counts in VARIABLES

{}'the'{'the': 1}'cat'{'the': 1, 'cat': 1}'and'{'the': 1, 'cat': 1, 'and': 1}'the'{'the': 2, 'cat': 1, 'and': 1}'dog'{'the': 2, 'cat': 1, 'and': 1, 'dog': 1}

opened with ▸

'the'2'cat'1'and'1'dog'1len()4
  1. 1 click just left of line 3's number: a breakpoint
  2. 2 the small arrow next to ▷ → Python Debugger: Debug Python File · type the cat and the dog in the terminal
  3. 3 Step Over (F10): counts appears in VARIABLES, empty
  4. 4 Step Over again and again: one word per iteration
  5. 5 after the loop: click ▸ next to counts
  6. 6 ▷ Continue: to the end
  7. Mac: F10 may need fn · or click the Step Over icon
Example · 3

Words by first letter

letters.py

Ask for a sentence. Print each first letter with the list of the words that start with it, the letters in the order they first come.

on the screen · one run

Sentence: coffee and cake at cafe

c: ['coffee', 'cake', 'cafe']

a: ['and', 'at']

the sentence after the prompt is typed · the prompt word is up to you

steps, in words

  1. 1 Ask for the sentence, and start with an empty dictionary.
  2. 2 For each word: if its first letter is already a key, add the word to that letter's list; if not, the letter gets a new list holding the word.
  3. 3 Print each letter with its list.

examples · typed values in order

typed

prints

coffee and cake at cafe

c: ['coffee', 'cake', 'cafe'], then a

big blue box

b: ['big', 'blue', 'box'] only

data

d: ['data'] only

Example · 3

Words by first letter: the program

letters.py

under the comments: one block per step

# Write your program here.

sentence = input("Sentence: ")

groups = {}

1

for word in sentence.split():

letter = word[0]

if letter in groups:

groups[letter].append(word)

else:

groups[letter] = [word]

2

for letter, words in groups.items():

print(f"{letter}: {words}")

3

on the screen · one run

Sentence: coffee and cake at cafe

c: ['coffee', 'cake', 'cafe']

a: ['and', 'at']

  1. 1 Ask for the sentence, and start with an empty dictionary.
  2. 2 For each word: if its first letter is already a key, add the word to that letter's list; if not, the letter gets a new list holding the word.
  3. 3 Print each letter with its list.
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']

Exercise 7

How to submit

  1. 1 download week09_exercise.zip from e-Class · unzip it: three files, one per problem
  2. 2 put the three files in python_course/week09 · open them in VS Code
  3. 3 in each file: write your program at the bottom · save · run it and try every example
  4. 4 zip the three files · upload the zip on e-Class · the deadline is in the post
10 points: 2 · 3 · 5attempted: full points, right or wronglate: half the pointsAI: allowed, but try alone first

Next steps

Now: exercise 7.

Before class. Everything you need is on e-Class.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space