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

{"host": "example.com", "port": 443}

Standard mapping literal.

Constructor

dict(host="example.com", port=443)

Keyword form (string keys only).

Indexed get

d["host"]

Lookup; raises KeyError on miss.

get

d.get("host")

Lookup; returns None on miss.

get with default

d.get("host", "")

Lookup; returns the supplied default on miss.

Assign

d["scheme"] = "https"

Insert or update.

del

del d["scheme"]

Remove; raises KeyError on miss.

pop

d.pop("scheme", None)

Remove and return; default on miss avoids KeyError.

Iteration walks keys; items() walks key-value pairs.

Form

Walks

for k in d

Keys, in insertion order.

for k, v in d.items()

Key-value pairs.

for v in d.values()

Values.

Merge and update.

Operation

Example

Effect

Merge

a | b

New dict; b wins on conflict.

Merge in place

a |= b

Update a with b’s entries.

Spread with extras

{**a, **b, "extra": 1}

New dict combining a, b, and additional pairs.

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

get(key[, default])

Lookup with optional default; never raises.

setdefault(key[, default])

Insert default if missing; return current value.

pop(key[, default])

Remove and return; default avoids KeyError.

popitem()

Remove and return the most-recently-inserted pair (3.7+).

update([other])

Merge another mapping or iterable of pairs in place.

clear()

Drop every entry.

copy()

Shallow copy.

keys()

View of keys (live; reflects mutation).

values()

View of values.

items()

View of (key, value) pairs.

dict.fromkeys(iterable[, value])

Build a dict with the given keys all mapped to value (classmethod).

__or__ / __ior__

d | other / d |= other for merge.

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

d[k]

__getitem__

Value at key; raises KeyError on miss.

d[k] = v

__setitem__

Insert or update.

del d[k]

__delitem__

Remove; raises KeyError on miss.

k in d

__contains__

Key membership test.

len(d)

__len__

Pair count.

iter(d)

__iter__

Iterate keys.

reversed(d)

__reversed__

Iterate keys in reverse insertion order (3.8+).

a == b

__eq__

Pairwise equality.

a | b

__or__

Merge into a new dict (3.9+).

a |= b

__ior__

In-place merge (3.9+).

bool(d)

__bool__

False only for the empty dict.

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#