Sobes.tech
Junior — Middle

What data types can serve as keys in Python dictionaries?

sobes.tech AI

Answer from AI

In Python, dictionary keys can only be immutable (hashable) data types. This means that the key must have a constant value and support the hash method.

Main key types:

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

Mutable types such as lists (list), sets (set), dictionaries (dict) cannot be used because they are not hashable.

Example:

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