Python Tutorial
Python Access Dictionary Items
Access a value by its key in square brackets, or with get() which can supply a default.
Accessing Items
[] raises KeyError if the key is missing. get() returns None or a default.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(thisdict["brand"])
print(thisdict.get("year"))
print(thisdict.get("color", "missing"))keys, values, items
These return views that stay in sync with the dictionary.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(thisdict.keys())
print(thisdict.values())
print(thisdict.items())
print("model" in thisdict)📘 Real-World Deep Dive
<code>dict[key]</code> is sharp: missing keys raise <code>KeyError</code>. Knowing <code>get/setdefault/operator.itemgetter</code> for safe reads keeps the rest of the code from filling with boilerplate guards.
Real-Life Scenario
A read-only lookup of user records: missing users should produce a sentinel, malformed requests should produce a clean 404 path.
Real-Life Example
from operator import itemgetter
from dataclasses import dataclass
@dataclass(frozen=True)
class User: id: int; name: str; email: str
USERS: dict[int, User] = {
1: User(1, "Ada", "ada@x"),
2: User(2, "Bo", "bo@x"),
3: User(3, "Cy", "cy@x"),
}
def fetch(uid: int) -> User | None:
return USERS.get(uid)
def fetch_or_default(uid: int) -> User:
return USERS.get(uid) or User(-1, "<unknown>", "")
def fetch_setdefault_count(uid: int) -> User:
return USERS.setdefault(uid, User(uid, f"user-{uid}", ""))
for uid in [1, 2, 99]:
u = fetch(uid)
print(f"fetch({uid}) -> {u}")
print()
for uid in [1, 2, 99]:
u = fetch_or_default(uid)
print(f"default({uid}) -> {u}")
# Tuple-style access
ids = [1, 2, 3]
get_name = itemgetter("name")
print("names:", [get_name(USERS[i].__dict__) for i in ids])Expected Output
fetch(1) -> User(id=1, name='Ada', email='ada@x')
fetch(2) -> User(id=2, name='Bo', email='bo@x')
fetch(99) -> None
default(1) -> User(id=1, name='Ada', email='ada@x')
default(99) -> User(id=-1, name='<unknown>', email='')
names: ['Ada', 'Bo', 'Cy']Common mistakes
d[k]on a missing key raisesKeyError; use.get()with a default.orsemantics vs.default:d.get(k) or fallbacktreats falsy values as missing —d.get(k, fallback)does not.setdefaultruns the value expression every call even if not used; preferif k not in dfor nontrivial defaults.
🚀 Performance & Best Practices
- Actively caching user records? Use a
functools.lru_cachewrapper aroundfetch. operator.itemgetteris C-fast — prefer over lambdas when you need many lookups.- Tuple unpacking
for k, v in d.items()is the best general-purpose access pattern.
🧪 Try It Yourself
- Add a
fetch_many(uids)returning alist[User]skipping missing IDs. - Profile
d.getvs.d[k]with a pre-existing key (expect zero practical difference). - Switch
fetch_or_defaultto use a typed sentinel instead of a sentinelUser(-1, ...).