2025-06-25
defaultdict vs dict
defaultdict
from collections import defaultdict
d = defaultdict(list)
d['key'].append('value') # Append directly without init
dict
d = {}
d['key'].append(1) # KeyError
d = {}
if 'key' not in d:
d['key'] = []
d['key'].append('value')
A tuple be used as a dictionary key
The key must be hashable.
key = (1, 2, 3)
print(hash(key))
In other words, Python must be able to compute hash(key), and the key must be immutable(its value cannot change)
A tuple cannot contain unhashable types(like lists or dicts)
key = ([1, 2], 3)
print(hash(key)) # TypeError: unhashable type: 'list'
hash()?
The hash() function returns an integer hash value for a given object.
why is hash() important?
In dictionaries or sets, Python uses hash() to decide where to:
- Decide where to store the key internally
- Quickly find the key without checking every element
This makes operations like insert and lookup super fast - average O(1) time.
print(hash("apple")) # Example: 2991632850760436371
print(hash(42)) # Example: 42
print(hash((1, 2, 3))) # Tuples are hashable
Behind the scenes in a dict
d = {"apple": 1}
- Python calls
hash('apple')internally - The resulting hash value helps determine the storage location quickly