Dictionaries
Looking up a key that is not in a dictionary stops the program with KeyError, but d.get(key, 0) returns 0 instead.
Seoyeon has 12 ballots and three candidates
That table is a dictionary. A dictionary stores pairs: a key, and the value that goes with it. You write it in curly braces, with a colon between each key and its value. To read a value, put the key in square brackets, the way you would put an index after a list. To add a pair or change one, assign to that key.
votes = {"Ari": 0, "Bo": 0, "Cy": 0}
votes["Bo"] = votes["Bo"] + 1
votes["Ari"] += 1
votes["Bo"] += 1
print(votes)
print(votes["Bo"]){'Ari': 1, 'Bo': 2, 'Cy': 0}
2Counting the whole box in one loop
Typing one line per ballot is no better than tally marks. Seoyeon puts the ballots in a list and loops over it. There is one snag: what if a ballot names someone she did not set up in advance, or she would rather not list the candidates first? Reading a missing key with square brackets stops the program. The method get(key, default) solves this. It returns the value if the key is there and the default if it is not, so votes.get(name, 0) + 1 works for the first vote and every vote after it.
ballots = ["Bo", "Ari", "Bo", "Cy", "Bo", "Ari",
"Cy", "Bo", "Ari", "Bo", "Cy", "Bo"]
votes = {}
for name in ballots:
votes[name] = votes.get(name, 0) + 1
print(votes)
print(len(ballots), sum(votes.values())){'Bo': 6, 'Ari': 3, 'Cy': 3}
12 12The last line is Seoyeon's check. Twelve ballots went in, and the counts add up to twelve, so none were lost. Notice the order of the names in the output: Bo first, because Bo was the first name the loop met. Since Python 3.7, a dictionary keeps its keys in the order they were first added, and the tutorial's section on dictionaries says the same.
Walking through keys and values together
A for loop over a dictionary gives the keys. items() gives key and value together, which is what you want for a results table. in checks whether a key exists, and max() with key=votes.get finds the key with the biggest value. That last one is a pattern worth copying as it is, even before every part of it makes sense.
votes = {"Bo": 6, "Ari": 3, "Cy": 3}
for name, n in votes.items():
print(name, "#" * n, n)
print("Dan" in votes)
print(max(votes, key=votes.get))Bo ###### 6
Ari ### 3
Cy ### 3
False
BoDictionaries turn up wherever data comes in name and value pairs: a word and its meaning, a subway station and its line number, a student number and a name. Keys must be unique, and assigning to an existing key replaces its old value rather than adding a second copy.
| dictionary | Key: value pairs in { } |
| key | The name you look a value up by; keys are unique |
| d[key] | Reads the value; KeyError if the key is missing |
| d.get(key, default) | Reads the value, or gives the default if the key is missing |
| d.items() | Key and value pairs for a for loop |
| key in d | True if the dictionary has that key |
- What does this print?
price = {"gimbap": 3500, "ramen": 4500} print(price["ramen"]) - What does this print?
price = {"gimbap": 3500} price["tteokbokki"] = 5000 print(len(price)) - What does this print?
price = {"gimbap": 3500} price["gimbap"] = 4000 print(price) - What does this print?
stock = {"pens": 4} print(stock.get("pens", 0), stock.get("tape", 0)) - What happens when this runs?
stock = {"pens": 4} print(stock["tape"])- It prints 0
- It prints None
- It prints tape
- It stops with KeyError: 'tape'
- What does this print?
counts = {} for ch in "hello": counts[ch] = counts.get(ch, 0) + 1 print(counts["l"]) - What does this print?
ages = {"Mina": 14, "Jun": 13} print("Jun" in ages, 14 in ages) - What does this print?
d = {"b": 2, "a": 1} for k in d: print(k)a
bb
a2
1b 2
a 1
- What does this print?
scores = {"Ari": 3, "Bo": 6, "Cy": 3} print(max(scores, key=scores.get)) - What does this print?
d = {"x": 1, "y": 2} total = 0 for k, v in d.items(): total += v print(total)
- "votes["Dan"] gives 0 if Dan got no votes." If "Dan" was never added as a key, the lookup stops with KeyError: 'Dan'. Use votes.get("Dan", 0) when a key may be missing.
- "14 in ages checks whether anyone is 14." in looks at keys, not values. To search the values, write 14 in ages.values().
- "Dictionaries have positions like lists, so votes[0] is the first candidate." A dictionary is looked up by key, not by position. votes[0] looks for a key equal to 0 and gives KeyError: 0.
- A dictionary stores key: value pairs in { }.
- d[key] reads a value; a missing key gives KeyError.
- d.get(key, default) avoids the KeyError.
- counts[x] = counts.get(x, 0) + 1 is the counting pattern.
- for k, v in d.items(): walks through pairs in the order they were added.
Sources for this course (6)
- Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
- Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
- Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
- General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
- Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
- Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)
Checked: 2026-10-19