Python Tutorial 0/52 lessons ~6 min read Lesson 20
Dictionaries
Dicts are hash maps — O(1) get/set/delete.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Dicts are hash maps — O(1) get/set/delete. Insertion-ordered since Python 3.7. The most-used data structure in Python.
Understanding the topic
Core concepts to understand:
{'k': 'v'}ordict().d.get(k, default)avoids KeyError.d.setdefault,collections.defaultdict.- Iterate:
items(),keys(),values().
Syntax reference
Visual flow / code:
python
user = {"id": 1, "name": "Alice", "role": "admin"}user["email"] = "a@x.com" # adduser.pop("role") # removename = user.get("name", "?")# Iteratefor k, v in user.items():print(f"{k}: {v}")# defaultdict — auto-init missing keysfrom collections import defaultdictcounts = defaultdict(int)for c in "hello":counts[c] += 1# Dict merge (3.9+)merged = {"a": 1} | {"b": 2}
Execution workflow
1Dictionaries Workflow
1 / 4{'k'
'v'} or dict().
Real-world use
Dicts are the JSON of Python: every API response, config file, and DB row maps to/from a dict. Master get, setdefault, and defaultdict.
Best practices
- Use
getwith defaults to avoid KeyError. - defaultdict for grouped/counted data.
- Use
Counterfor histograms.
Common mistakes
- Mutating a dict during iteration → RuntimeError.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionDict vs list lookup?+
Answer
A dict lookup by key is O(1) on average through hashing, while finding an item in a list by value is an O(n) scan. A list is better for ordered, index-based access, and a dict is better for key-based lookup. Keys must be hashable.
2BeginnerQuestionWhat's defaultdict?+
Answer
collections.defaultdict is a dict subclass that calls a factory function, like list or int, to create a missing value when a key is accessed with []. It removes the need for setdefault or checking if key in d. Be aware that merely reading a missing key inserts it.Follow-up
What does defaultdict do on d.get(missing)?
3BeginnerQuestionAre dicts ordered?+
Answer
Yes. Since Python 3.7 the language guarantees that dicts preserve insertion order (it was an implementation detail of CPython 3.6). Updating the value of an existing key keeps its position, while deleting and re-adding moves it to the end. Equality between dicts ignores order, unlike
OrderedDict comparisons.Follow-up
How does OrderedDict still differ from dict?
Summary
In summary: O(1) hash map; insertion-ordered. get/setdefault/defaultdict are everyday tools.
Ready to mark this lesson complete?Track your journey across the entire course.