Sobes.tech
Senior

What can be a dictionary key in Python?

sobes.tech AI

Answer from AI

In Python, a dictionary key can be any immutable (hashable) object. This means that the key must have a hash method and be comparable by value. Usually, the keys are:

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

Mutable types, such as lists, sets, or dictionaries, cannot be keys because they are not hashable.

Example:

my_dict = {
    1: 'one',
    'key': 'value',
    (1, 2): 'tuple key'
}