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
Foundation builder
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 / 4Step 1
{'k': 'v'} or dict().
Apply this step while implementing dictionaries in real code.
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.
Hands-on exercise
Interview preparation — practice these questions:
- Dict vs list lookup?
- What's defaultdict?
- Are dicts ordered?
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.