Skip to main content

Dictionaries

beginner12 min readLesson 18 of 169

Key→value lookups, safe .get(), and iterating pairs.

A dictionary maps keys to values — like a real dictionary maps words to definitions:

student = {"name": "Minh", "age": 21, "gpa": 3.6}
student["name"]           # 'Minh'
student["age"] = 22       # update
student["major"] = "CS"   # add a new key
del student["gpa"]        # remove

Safe lookups

Reading a missing key crashes:

student["phone"]          # KeyError!
student.get("phone")           # None
student.get("phone", "n/a")    # default value
"phone" in student             # membership check on keys

Iterating (preview)

for key in student:
    print(key, student[key])

for key, value in student.items():
    print(key, value)

.items() yields key–value pairs — the elegant way to walk a dict. Dicts are the natural shape for records: one student, one product, one setting — keys as field names.

Now practice

Dictionary DrillsKey-value lookups done safely.3 challenges · · ~30 min