Middle
Millised piirangud on dict võtmetele Pythonis?
sobes.tech AI
Vastus AI-lt
In Python, keys in a dictionary (dict) must be hashable (immutable) objects. This means that keys must have an unchangeable state and implement the __hash__() method.
Main restrictions:
- Keys must be immutable types, for example: strings (
str), numbers (int,float), tuples (tuple), provided all elements of the tuple are also hashable. - Mutable types such as lists (
list), sets (set), dictionaries (dict) cannot be used as keys because they are not hashable.
Example:
valid_dict = {
"key": 1,
42: "value",
(1, 2): "tuple key"
}
invalid_dict = {
[1, 2]: "list as key" # will raise TypeError
}
Trying to use a mutable object as a key will cause Python to raise a TypeError: unhashable type error.