Sobes.tech
Middle+

What can be a key in a dictionary or an element in a set in Python?

sobes.tech AI

Answer from AI

In Python, a key in a dictionary or an element of a set can be any object that is hashable (immutable and with a defined hash method).

This means that keys and set elements must:

  • Be immutable (for example, numbers, strings, tuples with immutable elements).
  • Support the hash and eq methods for correct comparison.

Examples of valid keys/elements:

  • int, float, str
  • tuples (tuple), if all elements are also hashable

Invalid:

  • lists (list), dictionaries (dict), sets (set), as they are mutable and not hashable.

Example:

my_dict = {('a', 1): 'value', 42: 'answer'}
my_set = {1, 'hello', (2, 3)}
What can be a key in a dictionary or an element in a… - sobes.tech