Dictionaries (records) · 딕셔너리(레코드)
Store data by name
- A dictionary stores values under names called keys.
- Write pairs inside braces:
{"name": "Sam", "age": 15}. - Each key is unique and points to one value.
Get and set values
- Read a value with its key:
person["name"]. - Add or change a value the same way:
person["age"] = 16. - A list uses a number index; a dictionary uses a key.
ages = {"Sam": 12, "Mia": 15}
print(ages["Sam"])
ages["Leo"] = 9
print(ages)
A dictionary as a record
- A record groups related facts about one thing.
- A dictionary is a neat way to hold a record.
- Each key is a field, like
nameorgrade.
pupil = {"name": "Ada", "grade": "A"}
print(pupil["name"])
print(pupil["grade"])
Check and loop
"name" in personisTrueif that key exists.for key in person:visits each key in turn.person.get("x", 0)returns a default if the key is missing.
menu = {"tea": 2, "cake": 5}
for item in menu:
print(item, menu[item])
print("tea" in menu)
In Cambridge pseudocode
- A dictionary models the exam's
TYPErecord; each key is a field reached with a dot.
TYPE Student
DECLARE Name : STRING
DECLARE Age : INTEGER
ENDTYPE
DECLARE Pupil : Student
Pupil.Name ← "Sam"
Pupil.Age ← 15
Common mistakes
- Read a value by its key:
d["name"]; a missing key raises a KeyError. - Keys are unique — assigning the same key again overwrites the value.
- Use
d.get(key)when the key might be missing.
Now you try
- Build or update a dictionary in each task.
- Press Check answer to test your code.
Look up by key · 키로 검색하기
A dictionary jumps straight to the value for a key — no scanning. · 딕셔너리는 키에 대한 값으로 직접 이동합니다 — 스캔할 필요가 없습니다.
Create a dictionary book with two keys: title set to "Python" and pages set to 200. · 두 개의 키를 가진 딕셔너리 book을 생성하십시오: title은 "Python"로, pages은 200로 설정합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
The dictionary student already has name and score. Change score to 85, and add a new key passed set to True. · 딕셔너리 student은 이미 name과 score을 가지고 있습니다. score을 85로 변경하고, 새로운 키 passed을 True로 추가하십시오.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Loop over the dictionary prices and add up its values. Store the total in total (the answer is 10). · 딕셔너리 prices을 순회하며 값을 더합니다. 합계를 total에 저장합니다 (정답은 10).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write count_words(text) that returns a dictionary: each word of text (split on spaces) mapped to how many times it appears. count_words("the cat and the hat") gives {"the": 2, "cat": 1, "and": 1, "hat": 1}. · count_words(text)을 작성하여 셔너리를 반환하십시오: text의 각 단어(공백 기준으로 분리)가 나타나는 횟수로 매핑됩니다. count_words("the cat and the hat")은 {"the": 2, "cat": 1, "and": 1, "hat": 1}을 제공합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.