xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Dictionaries

Data structures5 min readLesson 2 of 3

Minutes: 5

A dictionary maps keys to values. Lookup by key does not scan the items.

python
student = {"name": "Ada", "score": 92}
student["score"]          # 92
student["grade"] = "A"    # add a new key
student.get("email", "not set")

get is the safe read: a missing key returns the default instead of raising. [] raises KeyError, which is useful when a missing key really is a bug.

Iterating gives keys by default; ask for what you need:

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

Counting is the classic use:

python
counts = {}
for word in ["a", "b", "a"]:
    counts[word] = counts.get(word, 0) + 1

Dicts keep insertion order, and since Python 3.7 that order is guaranteed by the language.