Can you use a namedtuple as a dictionary key? Explain why or why not based on Python's data model.

Python interview question for Advanced practice.

Answer

Yes, a namedtuple can be used as a dictionary key if and only if all its elements are hashable. Reasoning: A namedtuple is a subclass of tuple. Tuples are immutable and are hashable by default. Because dictionary keys in Python must be hashable (to maintain stable positions in the hash table), namedtuple is an excellent choice for complex, multi-part keys (e.g., using Point(x, y) as a coordinate key). However, if the namedtuple contains a mutable object (e.g., Record(id=1, tags=[])), it becomes unhashable and will raise a TypeError if used as a key.

Explanation

A namedtuple containing a mutable list is NOT hashable and cannot be used as a key.

Related Questions