Python 3.15+Built-in functionsterm
frozendict()
types
An immutable dictionary: the same keys and lookups as dict, but no in-place changes. Hashable when its keys and values are hashable.
Syntax
frozendict(**kwargs)
frozendict(mapping, /, **kwargs)
frozendict(iterable, /, **kwargs)
The main benefit is hashability: a frozendict can go into a set, serve as a key of another dict or as an argument to a functools.cache function, which a dict cannot. Mutating methods (d[k] = v, del, pop, update, setdefault, clear) are absent, and an attempt to write raises TypeError. The | operator returns a new frozendict, and |= rebinds the name to a new object instead of changing it. It is not a dict subclass: isinstance(fd, dict) is false, but frozendict is a Mapping. Hashability is shallow: a frozendict holding a list can be created, but hash() on it fails with TypeError. Before 3.15 a similar role was played by types.MappingProxyType, but that is only a view of another dict and changes along with it.
Examples
fd = frozendict(host='localhost', port=8080)
print(fd['port']) # → 8080
print(fd) # → frozendict({'host': 'localhost', 'port': 8080})
try:
fd['port'] = 9090
except TypeError as e:
print(type(e).__name__) # → TypeError
configs = {frozendict(env='prod'): 'боевой', frozendict(env='dev'): 'отладка'}
print(configs[frozendict(env='dev')]) # → отладка
print(isinstance(frozendict(), dict)) # → False
base = frozendict(a=1)
more = base | {'b': 2}
print(more) # → frozendict({'a': 1, 'b': 2})
print(base) # → frozendict({'a': 1}) — исходный не изменился
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy