← Back to all snippets
PYTHON

Using Frozenset as Dictionary Keys or for Immutable Sets

Leverage Python's `frozenset` for immutable and hashable sets, enabling their use as dictionary keys or as elements within other sets.

# Problem: Regular sets are mutable and cannot be used as dictionary keys
# my_set = {'a', 'b'}
# my_dict = {my_set: 'value'} # This would raise a TypeError: unhashable type: 'set'

# Solution: Use frozenset for immutable (hashable) sets
permissions_level_1 = frozenset({'read', 'write'})
permissions_level_2 = frozenset({'read', 'write', 'delete'})
permissions_level_3 = frozenset({'admin'})

# frozenset can be used as a dictionary key
role_access = {
    permissions_level_1: "Standard User",
    permissions_level_2: "Power User",
    permissions_level_3: "Administrator"
}

print(f"Access for {'read', 'write'}: {role_access[frozenset({'read', 'write'})]}")
# Output: Access for {'read', 'write'}: Standard User

# frozenset can also be an element of another set
all_permission_sets = {permissions_level_1, permissions_level_3}
print(f"All defined permission sets: {all_permission_sets}")
# Output: All defined permission sets: {frozenset({'read', 'write'}), frozenset({'admin'})}

# Example: Grouping data by unique combinations of tags
products_with_tags = [
    {"name": "Chair", "tags": frozenset({"furniture", "home")}},
    {"name": "Desk", "tags": frozenset({"furniture", "office")}},
    {"name": "Lamp", "tags": frozenset({"home", "lighting")}},
    {"name": "Bookshelf", "tags": frozenset({"home", "furniture")}},
]

# Group products by their exact tag combination
products_by_tags = {}
for product in products_with_tags:
    tags = product["tags"]
    if tags not in products_by_tags:
        products_by_tags[tags] = []
    products_by_tags[tags].append(product["name"])

print("
Products grouped by tags:")
for tags, names in products_by_tags.items():
    print(f"{sorted(list(tags))}: {names}")
# Output:
# ['furniture', 'home']: ['Chair', 'Bookshelf']
# ['furniture', 'office']: ['Desk']
# ['home', 'lighting']: ['Lamp']
How it works: While regular `set` objects are mutable and thus unhashable, `frozenset` is an immutable version of a set. This immutability makes `frozenset` hashable, allowing it to be used as a key in a dictionary or as an element within another set. This is particularly useful in web applications for scenarios where you need to uniquely identify or group data based on a combination of items (e.g., permissions, tags, feature flags) where the order doesn't matter, but the exact collection of items does.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs