Python Dictionaries
A dictionary maps keys to values. Since Python 3.7 it remembers insertion order. Probably the most useful collection in the language.
Create & access
PYTHON
user = {'name': 'Ada', 'age': 36}
user['email'] = 'ada@example.com' # set
print(user['name']) # Ada
print(user.get('phone', 'n/a')) # n/a — get() takes a default
Iterate
PYTHON
for k in user: # keys
print(k)
for v in user.values():
print(v)
for k, v in user.items():
print(k, v)
Useful methods
| Method | What it does |
|---|---|
get(k, default) | Read; returns default if missing. |
setdefault(k, default) | Insert default if missing, then return value. |
update(other) | Merge another dict in. |
pop(k) | Remove and return. |
keys() / values() / items() | Views into the dict. |
Comprehensions
PYTHON
squares = {n: n * n for n in range(1, 6)}
inverted = {v: k for k, v in user.items()}
Merge operators (3.9+)
PYTHON
a = {'x': 1, 'y': 2}
b = {'y': 99, 'z': 3}
c = a | b # {'x': 1, 'y': 99, 'z': 3}
a |= b # in-place merge
Tip: Keys must be hashable (immutable) — strings, ints, tuples of immutables. Lists and dicts can't be keys.
Example
Example
user = {'name': 'Ada', 'age': 36}
user['email'] = 'ada@example.com'
for k, v in user.items():
print(k, v)
print(user.get('phone', 'n/a'))
Try it Yourself »
Exercise
Safely read a missing key with a default value.
user.
('phone', 'n/a')
Three letters.
Discussion
Loading…