What is the time complexity of searching a Python dictionary (`dict`), and what can be used as a dictionary key?
Asked at
AI answer
On average, a lookup by key in a dict takes O(1): Python uses the key’s hash and a hash table. In the worst case, for example when there are many collisions, a lookup can take O(n). A key must be hashable: it must have a stable hash and correct equality comparisons. That’s why immutable types are usually suitable (str, int, a tuple of hashable elements, frozenset), but immutability alone does not guarantee hashability. Lists and ordinary sets cannot be used as keys.
Also asked at СБЕР
- Do you have any questions about the company and the role?
- Tell us about your experience: on which projects you worked at [company] and [company], what technologies you used, and what you were responsible for?
- Tell us about yourself: how did you come into development, what teams and products have you worked on, what functionality did you perform?
- What databases have you had to work with as a developer?
- Tell me about the product/project you worked on and your main tasks.
Similar questions
- Compare the speed of checking whether an element is present in a list, dict, and set; how do collisions and lookup with open addressing work? What happens when an element is deleted?
- What can be used as a dictionary key? Can a tuple be used?
- What types of objects can be used as dictionary keys in Python, and how are the `__hash__` and `__eq__` methods related?
- How does lookup in a set work?
- What can go wrong when looking up a key in a dictionary, and what is the worst-case time complexity?