Frozen icicles evoking the notion of a “frozen” set in Python

Using Tuples and Frozensets as dictionary keys in Python

Anurag Chatterjee
2 min readJul 24, 2023

--

Tuples and frozensets are the immutable i.e. unchangeable versions of lists and sets respectively. One of the benefits of the immutability is that these data structures are hashable. So there can be a unique hash for a tuple and a frozenset. This also means that they can be used as keys in a dictionary while their mutable counterparts i.e. lists and sets cannot be used as dictionary keys.

Why are they hashable?

Since these data types are immutable it means once these are created the values cannot be changed and so the hash value will always be the same.

>>> my_set = set([1, 2, 1, 3])
>>> hash(my_set) # set cannot be hashed!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> my_frozenset = frozenset([1, 2, 1, 3])
>>> hash(my_frozenset)
-272375401224217160
>>> another_frozenset = frozenset([1, 2, 3, 1])
>>> hash(another_frozenset) # Hash value should be same as before as elements are the same
-272375401224217160
>>> my_tuple = (1, 2, 1, 3)
>>> hash(my_tuple)
-3261335203891832775
>>> my_tuple = (1, 2, 3, 1)
>>> hash(my_tuple) # hash values of the tuples are different as the order of elements are different
-3132950713063864564

When to use tuples and frozensets as dictionary keys?

When used in dictionary, using these types makes a difference.

In case the order of the items in the key matters then tuples should be used as dictionary key.

In case the order of the items in the key does not matter and duplicates can be ignored then a frozenset can be used as the dictionary key.

>>> dict1 = {(1,2): "ab", (2,1):"cd"}
>>> (1,2) in dict1 # Check if the tuple exists in the dictionary dict1
True
>>> dict1 # 2 different elements as order of elements in a Tuple matters
{(1, 2): 'ab', (2, 1): 'cd'}

>>> dict3={frozenset([1,2]):"ab"}
>>> dict3[frozenset([2,1,1])]="cd" # Update existing element in the dictionary
>>> dict3
{frozenset({1, 2}): 'cd'}
>>> frozenset([2,1]) in dict3
True
>>> frozenset([1,2]) in dict3
True
>>> frozenset([1,2,2,1]) in dict3 # Order of items and duplicates are ignored
True

--

--

Anurag Chatterjee
Anurag Chatterjee

Written by Anurag Chatterjee

I am an experienced professional who likes to build solutions to real-world problems using innovative technologies and then share my learnings with everyone.

Responses (2)