Python Programming · Week 9
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
>>>book = {"Kim": 85, "Lee": 72, "Park": 93}
>>>book
{'Kim': 85, 'Lee': 72, 'Park': 93}
>>>len(book)
33 pairs
>>>{}
{}an empty dictionary
a dictionary: key-value pairs · each key leads to its value
a dictionary · by key
>>>book = {"Kim": 85, "Lee": 72, "Park": 93}
>>>book["Park"]
93
>>>book["Kang"]
KeyError: 'Kang'
a list · week 7 · by position
>>>scores = [85, 72, 93, 60]
>>>scores[2]
93
>>>book = {}
an empty dictionary
>>>book["Kim"] = 85
a new key: added
>>>book["Lee"] = 72
added at the end
>>>book["Kim"] = 90
a key already there: changed
>>>{"Kim": 85, "Kim": 90}
{'Kim': 90}one key, one value
a key appears only once · the last value stays
>>>book = {"Kim": 85, "Lee": 72, "Park": 93}
>>>"Park" in book
True
>>>"Kang" in book
False
>>>85 in book
False
in looks at the keys
in: is the key there? · get: no KeyError, None or a default
book = {"Kim": 85, "Lee": 72, "Park": 93}
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
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
book = {"Kim": 85, "Lee": 72, "Park": 93}
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
>>>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)
each pair becomes a key and its value · dict(zip(keys, values))
a list of dictionaries · a position, then a key
>>>students = [{"name": "Kim", "score": 85},
... {"name": "Lee", "score": 72}]
>>>students[1]["score"]
72
↓
a dictionary of lists · a key, then a position
>>>marks = {"Kim": [85, 90], "Lee": [72, 65]}
>>>marks["Kim"][1]
90
↓
from the outside in · one step at a time
>>>{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
set
a set: no duplicates · no positions
>>>a = {1, 2, 3, 5}
>>>b = {2, 3, 4}
>>>4 in b
True
>>>a | b
{1, 2, 3, 4, 5}
>>>a & b
{2, 3}
a | b: in either set · a & b: in both
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]
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
No computer. Say what comes out, then I run it.
>>>teams = {"red": ["Kim", "Lee"], "blue": ["Park"]}
>>>len(teams)
>>>teams["red"][-1]
>>>dict(zip("abc", [1, 2, 3]))
>>>{1, 2, 3} & {4, 5}
>>>type({})
>>>[ch for ch in "hello" if ch != "l"]
quiz5.py
cart = {"apple": 2, "pear": 3}
total = 0
for x in cart:
total += x
print(total)
quiz6.py
prices = {"tea": 3, "cake": 5}
total = 0
for item in ["tea", "juice", "cake"]:
total += prices.get(item, 0)
print(total)
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
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
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
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
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