Interview question
How does a Python dictionary work internally? - Data Types and Data Structures Python dictionary internally कैसे काम करता है?
Answer
# Hash function
hash('key') # Returns hash value
hash('hello') # 8730470218056277053
# O(1) lookup
my_dict = {'name': 'John', 'age': 30}
print(my_dict['name']) # O(1) average time
# Dictionary is hash table
# 1. Hash the key
# 2. Map to index in table
# 3. Retrieve value at index
# Why dicts are fast vs lists
big_dict = {x: x for x in range(1000000)}
big_list = list(range(1000000))
# Dict: O(1)
# List: O(n) - 1000x slower!
# Key must be hashable (immutable)
my_dict[(1, 2)] = 'tuple key' # Works - hashable
try:
my_dict[[1, 2]] = 'list key' # Error - not hashable
except TypeError:
passhash('key') # Hash value return करता है
my_dict = {'name': 'John'}
print(my_dict['name']) # O(1) average
# Dictionary hash table है
# Key को hash करो -> index -> value retrieve करो
# Tuple key बन सकता है
my_dict[(1, 2)] = 'value' # काम करता है
# List key नहीं बन सकता
try:
my_dict[[1, 2]] = 'value' # Error
except TypeError:
passWas this answer clear?