Junior — Middle
How can a set be used as a key in a Python dictionary?
sobes.tech AI
Answer from AI
In Python, a set cannot be used directly as a dictionary key because sets are mutable and unhashable.
If you need to use a set as a key, you can use frozenset — an immutable and hashable version of a set.
Example:
my_dict = {}
key = frozenset([1, 2, 3])
my_dict[key] = "value"
print(my_dict[frozenset([1, 2, 3])]) # Outputs: value
Thus, frozenset allows you to use a set as a dictionary key.