Sobes.tech
Junior — Middle

How can you determine if an object can be safely used as a hash key?

sobes.tech AI

Answer from AI

An object can be used as a key in a dictionary or as an element of a set if it is hashable. In Python, this means that the object must satisfy two conditions:

  1. Have a __hash__() method that returns an immutable integer value.
  2. Have a correctly implemented __eq__() method so that objects considered equal have the same hash.

Additionally, the object must be immutable, as changing the object after using it as a key will break the integrity of the hash table.

Example:

# Tuple — hashable type
key = (1, 2, 3)
d = {key: 'value'}

# List — not hashable, will cause an error
key = [1, 2, 3]
d = {key: 'value'}  # TypeError

To check if an object can be used as a key, you can call hash(obj) and ensure that no exception is raised.