Sobes.tech
Junior — Middle

What are the main conditions and rules for using keys in Python dictionaries?

sobes.tech AI

Answer from AI

In Python, dictionary keys must meet the following conditions:

  • Be hashable. This means the object must have an immutable state and implement the __hash__() method.
  • Be comparable for equality via __eq__(), so that the dictionary can correctly determine if keys are the same.

Most often, immutable data types are used as keys, such as:

  • Strings (str)
  • Numbers (int, float)
  • Tuples (tuple), if all their elements are also hashable

Example:

my_dict = {}
my_dict["key"] = 123
my_dict[(1, 2)] = "tuple key"

Trying to use a mutable type, like a list, as a key will result in a TypeError:

my_dict = {}
my_dict[[1, 2]] = "list key"  # TypeError: unhashable type: 'list'

Therefore, keys must be immutable and hashable objects so that the dictionary can efficiently store and retrieve values.