Loading lessons...
Dictionary Methods Reference
Dictionary Methods Reference
The most useful dictionary methods in one table.
| Method | Job |
|---|---|
clear() | Remove all items |
copy() | Return a copy |
fromkeys(seq, v) | New dict from a sequence with one value |
get(key) | Get a value safely |
items() | View of key-value pairs |
keys() | View of keys |
pop(key) | Remove and return a value |
popitem() | Remove the last item |
setdefault(key, v) | Get value, or set it if missing |
update() | Merge in another dict |
values() | View of values |
Examples
d = {"a": 1, "b": 2}
print(d.setdefault("c", 3)) # 3, and d now has "c": 3
print(d.get("z", "missing")) # missing
The views are live
keys(), values(), and items() update if the dictionary changes.
TL;DR
- get, setdefault, update read and write safely.
- keys, values, items show views of the data.
- pop, popitem, clear, del remove items.
- fromkeys builds a dict from a sequence.