Dictionaries
Dictionary Basics
Creating and using dictionaries
Interview: Most important Python data structure — essential for all interviews
Dictionaries are Python's built-in hash map implementation — mutable, unordered (insertion-ordered in 3.7+) collections of key-value pairs. They provide O(1) average-case lookup, insertion, and deletion, making them one of the most important data structures.
Creating Dictionaries
- Literal:
{"key": "value"} - Constructor:
dict(key="value")ordict([("a", 1)]) - From zip:
dict(zip(keys, values)) - Comprehension:
{k: v for k, v in pairs} - Empty:
{}ordict()
Key Requirements
- Keys must be hashable (immutable): strings, numbers, tuples of immutables
- Keys must be unique: duplicate keys use the last value
- Values can be any type: including lists, dicts, functions, classes
Performance
- Lookup: O(1) average, O(n) worst case (hash collisions)
- Insert/Delete: O(1) average
- Memory: Higher than lists due to hash table overhead (sparse array)
- Python 3.6+ dicts maintain insertion order as an implementation detail; guaranteed in 3.7+
Interview Tip
Know the difference between d[key] (raises KeyError) and d.get(key, default) (returns default). Using get() avoids try/except blocks for missing keys.
Use Cases
Key-value storage for configuration and settings
Frequency counting and grouping data
Caching/memoization (mapping inputs to outputs)
Dispatch tables replacing if-elif chains
Common Mistakes
Using d[key] without checking existence (KeyError) — use get() or check with in first
Using mutable objects (lists, dicts) as keys (TypeError: unhashable)
Forgetting that in operator checks keys only, not values
Not knowing that Python 3.7+ dicts maintain insertion order