Sobes.tech
Junior — Middle

What data types are suitable as dictionary keys in Python and why?

sobes.tech AI

Answer from AI

In Python, dictionary keys can only be immutable data types because keys need to be hashable for quick lookup. These types include:

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

For example, a list or a dictionary cannot be keys because they are mutable and do not have a fixed hash. Using immutable types ensures that the key does not change after being added to the dictionary, which is important for the correct functioning of the hash table.

Example:

my_dict = {
    42: 'number',
    'key': 'string',
    (1, 2): 'tuple'
}
print(my_dict[(1, 2)])  # Will output: tuple