dict — The Standard for Key-Value Storage
dict — The Standard for Key-Value Storage
🎯 After Reading This Lesson
After finishing this lesson, you will be able to confidently do the following 3 things.
- ▸✅ dict key requirements + collision handling
- ▸✅ Four methods: get · setdefault · pop · update
- ▸✅ dict comprehension + dict merging (PEP 584)
Keep the learning objectives as a checklist — close the lesson once you can answer all of them.
7 dict Patterns — Code + Execution Results
dict = key:value pairs. Fast lookup by name → value (lookup O(1)). Equivalent to Map·HashMap·Object in other languages.
1. Creating
{ key: value, key: value } — colon separates pairs, comma separates items.
2. Accessing Values
3. Adding · Updating · Deleting
4. Checking Existence — in
in on a list checks values, but in on a dict checks keys.
5. Iteration (for)
Execution result:
6. Nested dict (Real-world Pattern)
JSON and API responses look exactly like this — Python dicts are JSON-friendly.
7. Common Pattern — Counter
get(key, 0) = "return the value if it exists, otherwise 0" — the core of counting and accumulation patterns.
list vs dict — When to Use Which?
One-line Summary
🐍 Try It Yourself — dict — Run It Directly
🤖 Try Asking AI Like This
Knowing the concepts from this lesson lets you give AI specific instructions. Instead of a vague 'fix this', you make vocabulary-backed requests — that is where token savings begin.
- ▸'Replace this list deduplication with a set'
- ▸'Rewrite this dict merge using dict | dict (Python 3.9+)'
Why Does This Reduce Tokens?
Without understanding the concepts, you have to ask 'What does that mean?' after receiving an AI response. Those follow-up questions consume tokens. Master the concept once and the conversation ends in a single round.