Sobes.tech
Junior

What can be a key in a Python dictionary?

sobes.tech AI

Answer from AI

In Python, a dictionary key can be any immutable and hashable object. This means that the key must have:

  • A __hash__() method that returns a hash code.
  • An __eq__() method for comparison with other keys.

Typical examples of keys:

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

Example:

my_dict = {
    42: 'number',
    'key': 'string',
    (1, 2): 'tuple'
}

Mutable types such as lists, sets, or dictionaries cannot be keys because their contents can change, which would break the integrity of the hash table.