Sobes.tech
Junior

What can be keys in dictionaries in Python?

sobes.tech AI

Answer from AI

Keys in Python dictionaries can be any immutable (hashable) objects.

Immutable data types include:

  • Integers (int)
  • Floating-point numbers (float)
  • Strings (str)
  • Tuples (tuple) containing only immutable elements
  • Boolean values (bool)
  • NoneType (None)
  • Frozenset (frozenset) containing only immutable elements

Examples of valid keys:

# Valid keys
my_dict = {
    1: "one",
    3.14: "pi",
    "key": "value",
    (1, 2): "tuple",
    True: "truth",
    None: "no",
    frozenset({1, 2}): "immutable set"
}

Immutable objects have a hash value, which is used for quick lookup in the dictionary.

Mutable data types, such as lists (list), sets (set), and other dictionaries (dict), cannot be used as dictionary keys because their contents can change, which would break hash integrity.

Examples of invalid keys:

# Invalid keys (will raise TypeError)
# my_dict = {
#     [1, 2]: "list",
#     {1, 2}: "set",
#     {"a": 1}: "another dict"
# }