Sobes.tech
Middle

Can (1, [1, 2]) be used as a dictionary key in Python? Why?

sobes.tech AI

Answer from AI

In Python, a dictionary key must be an immutable object that supports hashing (has a __hash__ method). A tuple (1, [1, 2]) contains a list [1, 2], which is mutable and not hashable. Therefore, such a tuple cannot be used as a dictionary key, as attempting to do so will result in a TypeError: unhashable type: 'list'.

Example:

key = (1, [1, 2])
d = {}
d[key] = 'value'  # TypeError: unhashable type: 'list'

If you want to use a tuple as a key, all its elements must be hashable, for example, (1, (1, 2)) — a tuple with a nested tuple.