SkilDock
All Python tutorialsFree interactive tutorial

Python Dictionaries — Beginner Tutorial

Learn Python dictionaries with examples. Keys, values, looping, the .get() trick, and why dicts give you O(1) lookups. Includes a browser code editor.

Try it in your browser

Runs in your browser via Pyodide — no signup, no install. Want auto-graded full exercises + videos? See the 7-Day Python Sprint.

A dictionary is a collection of key-value pairs — Python's equivalent of a hash map. You create one with curly braces and colons:

prices = {"apple": 50, "banana": 30, "mango": 80}
user = {"name": "Alice", "age": 30, "city": "Bangalore"}

Dicts give you O(1) average lookup — instant access by key no matter how big the dict is. That's why they show up everywhere in real Python code: caching, counting, indexing, configuration.

Basic operations

prices["apple"]              # 50 — looking up a key
prices["mango"] = 100        # update a value
prices["cherry"] = 120       # add a new key
del prices["banana"]         # remove a key
"apple" in prices            # True — checks KEYS, not values
len(prices)                  # 3

Looping a dict — three patterns

for key in prices:                # default — iterates keys
    print(key)

for value in prices.values():     # iterates values
    print(value)

for key, value in prices.items(): # iterates pairs — use this most
    print(f"{key}: {value}")

The .get() trick

Looking up a missing key raises a KeyError. Use .get() to provide a fallback:

prices["banana"]           # KeyError if banana isn't there
prices.get("banana")       # None — never crashes
prices.get("banana", 0)    # 0 — your custom default

This is the foundation of the most-used Python idiom — counting:

counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

Three lines, builds a word-frequency dict. Memorize the pattern; you'll use it for years.

Key rules

  • Keys must be hashable — immutable types: strings, numbers, tuples, frozensets. Lists *cannot* be keys.
  • Values can be anything — including other dicts (you'll see this with nested JSON).
  • Since Python 3.7, dicts preserve insertion order. Older code that imported OrderedDict from collections can usually drop it.

Dict comprehensions

Same shape as list comprehensions, with key: value:

squares = {n: n*n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

long_words = {w: len(w) for w in words if len(w) > 5}

Common mistakes

  • Confusing keys and values in in: "apple" in prices checks keys. To check values, use "apple" in prices.values() (which is O(n), not O(1)).
  • Default mutable values: defaultdict(list) from collections is your friend for the "collect items into a list per key" pattern.

Where this fits in the 7-Day Python Sprint

Dicts are introduced on Day 1, used for the contact-book lab, and become central on Day 7 when you build an Email Analyzer that groups emails by sender domain — straight dict counting.

Practice

Auto-graded — run in your browser, no signup.

Exercise 1: Add `'cherry': 120` to `prices`, then assign the total of all values to `total`.

Try it in your browser

Runs in your browser via Pyodide — no signup, no install. Want auto-graded full exercises + videos? See the 7-Day Python Sprint.

Like this tutorial? Get the full Python Sprint.

7 days, daily videos, auto-graded labs, AI tutor, mini-project. 1-year content access.

See the Python Sprint

Related tutorials