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'} or dict().
    • 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" # add
    user.pop("role") # remove
    name = user.get("name", "?")
    # Iterate
    for k, v in user.items():
    print(f"{k}: {v}")
    # defaultdict — auto-init missing keys
    from collections import defaultdict
    counts = defaultdict(int)
    for c in "hello":
    counts[c] += 1
    # Dict merge (3.9+)
    merged = {"a": 1} | {"b": 2}

    Execution workflow

    1Dictionaries Workflow
    1 / 4

    Step 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 get with defaults to avoid KeyError.
    • defaultdict for grouped/counted data.
    • Use Counter for 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.