Python 3 reference · Built-in Functions
Python frozendict() Function
Create an immutable, hashable dictionary (new in Python 3.15). It can be a dict key or set member and can't be changed.
Python 3 Since 3.15
Syntax
frozendict(**kwargs)
frozendict(mapping, **kwargs)
frozendict(iterable, **kwargs)
Parameters
| Parameter | Description |
|---|---|
mapping / iterable optional |
Another mapping, or an iterable of (key, value) pairs. |
**kwargs optional |
Extra keys as keyword arguments. |
Return value
A new frozendict.
Examples
config = frozendict(host="localhost", port=8080)
print(config["port"], len(config))
try:
config["port"] = 9000
except TypeError as e:
print("TypeError:", e)
Output
8080 2 TypeError: 'frozendict' object does not support item assignment
Run this on your computer — see “Get Started” for setup.
cache = {}
key = frozendict(user=1, page=2)
cache[key] = "rendered page"
print(cache[frozendict(page=2, user=1)]) # order doesn't matter
Output
rendered page
Run this on your computer — see “Get Started” for setup.
base = frozendict(a=1)
print(base | {"b": 2}) # creates a new frozendict
print(isinstance(base, dict))
Output
frozendict({'a': 1, 'b': 2})
FalseRun this on your computer — see “Get Started” for setup.
Good to know
frozendictis not a subclass ofdict, soisinstance(x, dict)isFalse. Check forcollections.abc.Mappingto accept both.- It is hashable only if all its values are hashable.
- On Python 3.14 and older,
types.MappingProxyType(dict(...))gives a read-only view, but it isn't hashable.
Version history
| Version | Change |
|---|---|
| Python 3.15 | Added |
Related
dict()· Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.frozenset()· Create an immutable set: unique items that can't be added or removed, so it is hashable and can be a dict key.hash()· Return the hash value of an object: an integer used by dicts and sets to find keys quickly. Only immutable values are hashable.tuple()· Create a tuple: an ordered, immutable sequence. Tuples are hashable when their items are, so they can be dict keys.- Python Dictionaries · tutorial