Frozensets
A frozenset is an immutable version of a set. Because it is hashable, it can be used as a dictionary key or as an element inside another set.
Creating Frozensets
fs = frozenset([1, 2, 3, 4, 4])
print(fs) # frozenset({1, 2, 3, 4})
print(type(fs)) # frozenset
empty_fs = frozenset()Read-Only Operations
print(3 in fs) # True
print(len(fs)) # 4
print(fs | frozenset({5, 6})) # union — returns new frozenset
print(fs & frozenset({2, 3})) # intersectionCannot Mutate
# fs.add(5) # AttributeError
# fs.remove(1) # AttributeErrorAs Dict Keys or Set Elements
# Sets of sets (impossible with mutable set)
s = {frozenset({1, 2}), frozenset({3, 4})}
print(s)
# As dict key
permissions = {
frozenset({"read", "write"}): "editor",
frozenset({"read"}): "viewer",
}
user_perms = frozenset({"read", "write"})
print(permissions[user_perms]) # editor