dict#
dict is Python’s key-value map. Insertion-ordered since
Python 3.7; keys must be hashable; values can be anything. The
operator’s default lookup table.
Daily kit on dict. Examples assume
d = {"host": "example.com", "port": 443}.
Operation |
Example |
Effect |
|---|---|---|
Literal |
|
Standard mapping literal. |
Constructor |
|
Keyword form (string keys only). |
Indexed get |
|
Lookup; raises |
|
|
Lookup; returns |
|
|
Lookup; returns the supplied default on miss. |
Assign |
|
Insert or update. |
|
|
Remove; raises |
|
|
Remove and return; default on miss avoids |
Iteration walks keys; items() walks key-value pairs.
Form |
Walks |
|---|---|
|
Keys, in insertion order. |
|
Key-value pairs. |
|
Values. |
Merge and update.
Operation |
Example |
Effect |
|---|---|---|
Merge |
|
New dict; |
Merge in place |
|
Update |
Spread with extras |
|
New dict combining |
Default values#
get returns a default without inserting; setdefault
inserts the default if missing and returns the value either way;
collections.defaultdict auto-creates a default on first
access.
Look up a key with an inline default; the dict is untouched on miss.
port = config.get("port", 8080)
Insert-and-return a default when the key is missing; useful for “get-or-create the bucket” patterns.
bucket = groups.setdefault(key, [])
bucket.append(item)
Reach for defaultdict when every missing key wants the same
factory.
from collections import defaultdict
counts = defaultdict(int)
for word in words:
counts[word] += 1
Fall-through-on-falsy with or when an empty / zero value
should be replaced by a default.
port = config.get("port") or 8080
Method catalog#
The full instance-method surface on dict.
Method |
Effect |
|---|---|
|
Lookup with optional default; never raises. |
|
Insert default if missing; return current value. |
|
Remove and return; default avoids |
|
Remove and return the most-recently-inserted pair (3.7+). |
|
Merge another mapping or iterable of pairs in place. |
|
Drop every entry. |
|
Shallow copy. |
|
View of keys (live; reflects mutation). |
|
View of values. |
|
View of (key, value) pairs. |
|
Build a dict with the given keys all mapped to |
|
|
get returns None (or a supplied default) on miss
instead of raising.
{"host": "example.com"}.get("port", 443)
443
setdefault inserts and returns the default when the key is
missing; idiomatic for “get-or-create the bucket”.
d = {}; d.setdefault("xs", []).append(1); d
{'xs': [1]}
pop removes and returns; with a default it never raises.
d = {"a": 1, "b": 2}; d.pop("a"), d
(1, {'b': 2})
dict.fromkeys builds a dict from an iterable of keys with a
uniform value.
dict.fromkeys("abc", 0)
{'a': 0, 'b': 0, 'c': 0}
Operator overloading#
dict implements the mapping protocol dunders.
Operator |
Dunder |
Returns |
|---|---|---|
|
|
Value at key; raises |
|
|
Insert or update. |
|
|
Remove; raises |
|
|
Key membership test. |
|
|
Pair count. |
|
|
Iterate keys. |
|
|
Iterate keys in reverse insertion order (3.8+). |
|
|
Pairwise equality. |
|
|
Merge into a new dict (3.9+). |
|
|
In-place merge (3.9+). |
|
|
|
A custom mapping uses __getitem__ / __setitem__ /
__len__ to behave like a dict in in, len, and
indexing.
class CaseInsensitiveDict:
def __init__(self): self._d = {}
def __getitem__(self, k): return self._d[k.lower()]
def __setitem__(self, k, v): self._d[k.lower()] = v
def __contains__(self, k): return k.lower() in self._d
def __len__(self): return len(self._d)
d = CaseInsensitiveDict(); d["Host"] = "example.com"
d["HOST"], "host" in d
('example.com', True)
Merge with | (3.9+); the right-hand dict wins on key
conflicts.
{"timeout": 30, "host": "a"} | {"host": "b"}
{'timeout': 30, 'host': 'b'}
References#
set for the unique-value container.
Data Structures for
defaultdict,Counter,OrderedDict,ChainMap.