Junior
What features should be considered when using numbers as keys?
sobes.tech AI
Answer from AI
When using numbers as keys in Python dictionaries, the following should be considered:
- Immutable: Numeric types (
int,float,complex) are immutable, making them suitable for use as dictionary keys. The hash value of a number is stable and does not change during the lifetime of the object. - Hashing: Python uses hashing for quick access to dictionary elements by key. Numbers have efficient hashing algorithms.
- Number types: While
intandfloatcan be keys,complexcan also be used, but their use as keys is less common. - Comparison: When comparing numeric keys, their value is considered. For example,
1(int) and1.0(float) may be considered different keys due to their type, even if their numeric value matches. However, when searching for a key, Python does not automatically convert types. The key'1'(string) is different from1(number).
Example:
# int and float as keys
my_dict = {1: 'integer one', 1.0: 'float one', 2: 'integer two'}
# Access by key
print(my_dict[1])
print(my_dict[1.0])
# print(my_dict['1']) # Error: KeyError