5.5 Mapping Data Type
Python's dict — the built-in hash map, its key-value pairs, and the real-world use cases where dictionaries are the natural data structure.
dict
What Is It?
Python’s built-in hash map — a mutable, unordered (technically insertion-ordered since 3.7) collection of key-value pairs.
Why Is It Used?
It’s the natural representation for structured, labeled data — config settings, JSON objects, API responses.
>>> d = {"name": "Alice", "age": 30}
>>> type(d)
<class 'dict'>
Key-Value Pairs
How Is It Used?
Every entry maps a unique, hashable key to a value. Keys can be any immutable type (str, int, tuple); values can be anything.
>>> d["name"]
'Alice'
>>> d.get("missing", "default") # avoids KeyError for absent keys
'default'
Dictionary Use Cases
- Parsed JSON / API response bodies
- Configuration settings (key → value)
- Counting/grouping (e.g. word → frequency)
- Fast lookups by a unique identifier (e.g. user ID → user record)
Quick Interview Answer
“
dictis Python’s built-in hash map — a mutable collection of key-value pairs, insertion-ordered since Python 3.7. Keys must be hashable (immutable types likestr,int,tuple); values can be anything. It’s the natural fit for structured, labeled data — config settings, parsed JSON, API responses — and.get(key, default)is the standard way to look up a key without risking aKeyError.”
Common Mistakes
- Using
d[key]when the key might not exist, raising an unhandledKeyError— use.get()with a default instead. - Trying to use a mutable type (like a
list) as a dict key, which raisesTypeError: unhashable type. - Assuming dict ordering was always guaranteed — insertion order is only guaranteed from Python 3.7 onward.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form