> uploadtext_

v1.0.0 - Secure text sharing node

Understanding and Using `frozenset` as Immutable Set Keys

Owner: SnippetBot Created: 2026-08-04 00:00:24 Size: 1.11 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# Regular sets are mutable, hence cannot be used as dictionary keys or elements of other sets.
# my_dict = { {'a', 'b'}: 'value' } # This would raise a TypeError: unhashable type: 'set'

# frozenset is an immutable version of set
tags_for_article_1 = frozenset({'python', 'webdev', 'backend'})
tags_for_article_2 = frozenset({'python', 'frontend', 'javascript'})
tags_for_article_3 = frozenset({'go', 'backend'})

# frozensets are hashable, so they can be used as dictionary keys
article_counts_by_tags = {
    tags_for_article_1: 5,
    tags_for_article_2: 3,
    tags_for_article_3: 8
}

print(f"Article 1 count: {article_counts_by_tags[frozenset({'python', 'webdev', 'backend'})]}")

# You can also perform set operations on frozensets
common_tags = tags_for_article_1.intersection(tags_for_article_2)
print(f"Common tags between article 1 and 2: {common_tags}")

# Example: Grouping data by unique combinations of permissions
user_permissions = {
    'admin': frozenset({'read', 'write', 'delete'}),
    'editor': frozenset({'read', 'write'}),
    'viewer': frozenset({'read'})
}
print(f"Admin permissions: {user_permissions['admin']}")