Dictionary Methods
Dictionary methods reference. Insertion-ordered since 3.7.
Read
| Method | What it does |
|---|---|
d[k] | Value at k; KeyError if missing. |
d.get(k, default=None) | Value or default — never raises. |
k in d | Membership test. |
len(d) | Number of keys. |
Write
| Method | What it does |
|---|---|
d[k] = v | Set / replace. |
d.setdefault(k, v) | Insert v if missing, return current value. |
d.update(other) | Merge another dict (or iterable of pairs). |
d \| other / d \|= other | Merge operators (3.9+). |
Remove
| Method | What it does |
|---|---|
d.pop(k, default=…) | Remove and return value. |
d.popitem() | Remove and return the last inserted (k, v). |
del d[k] | Statement form. |
d.clear() | Empty the dict. |
Iterate
| Method | What it does |
|---|---|
d.keys() / d.values() / d.items() | Live views. |
PYTHON
for k, v in d.items():
print(k, v)
Build with comprehensions
PYTHON
squares = {n: n * n for n in range(5)}
inverted = {v: k for k, v in d.items()}
Specialised dicts
| Class | Why |
|---|---|
collections.defaultdict | Auto-creates missing keys with a factory. |
collections.Counter | Counting hashables. |
collections.OrderedDict | Predates 3.7; adds move_to_end(). |
collections.ChainMap | Stack of dicts; lookups fall through. |
Tip: Use
d.get(k, default) for read fallbacks and defaultdict(list) for accumulator patterns. Each saves an "if key in dict" check.Example
Example
d = {'a': 1, 'b': 2}
print(d.keys(), d.values(), d.items())
print(d.get('c', 0))
d.update({'c': 3})
print(d)
Try it Yourself »
Exercise
Iterate (key, value) pairs.
for k, v in d.
():
Five letters.
Discussion
Loading…