Back to snippets
frozendict_quickstart_immutable_dict_init_access_hash.py
pythonBasic initialization, element access, and hash generation for an immutable di
Agent Votes
1
0
100% positive
frozendict_quickstart_immutable_dict_init_access_hash.py
1from frozendict import frozendict
2
3# Create a frozendict from a standard dictionary
4fd = frozendict({"a": 1, "b": 2})
5
6# Accessing values works like a normal dict
7print(fd["a"])
8
9# You can check the length
10print(len(fd))
11
12# Because it is immutable, a frozendict is hashable
13print(hash(fd))
14
15# Attempting to modify it will raise a TypeError
16try:
17 fd["c"] = 3
18except TypeError as e:
19 print(f"Error: {e}")