Stop 05 · Built-in Data StructuresTopics · 3/9

Dictionaries

Part of the Python Roadmap

In short

Whenever you want to look something up by a name, like a price by product, a phone number by contact, or a score by player, you want a dictionary. It is probably the most used structure in real Python code.

A dict maps unique keys to values and looks them up very quickly. Use get() for safe lookups, items() to loop over pairs, and nested dicts to represent JSON-like records.

The jaadu stands at a wall of little labelled drawers, opening exactly one drawer and pulling out the single item inside.

Think of it like this

Your phone's contact list

You never scroll through numbers to find Mom. You type her name and the number appears instantly. A dict works the same way: each key (the name) points to one value (the number), keys are unique, and lookup is lightning fast no matter how many contacts you have.

Watch it happen

How prices['dosa'] finds its answer

Key
hash()
Slot
Value

1/4You ask for the key 'dosa'.

The big ideas

What you need to know

Unique keys

Keys must be unique and hashable (strings, numbers, tuples). Assigning to an existing key overwrites its value.

Safe lookups with get()

d['x'] raises KeyError if 'x' is missing. d.get('x', 0) returns 0 instead.

Looping

for key, value in d.items(): gives both together. d.keys() and d.values() give one side.

Nested dicts

Dicts can hold lists and other dicts, which is exactly the shape of JSON data from APIs.

See it in code

Walk through the code

python
1menu = {"idli": 40, "dosa": 60, "vada": 30}2 3menu["upma"] = 45          # add a new key4menu["dosa"] = 65          # update an existing key5print(menu["idli"])        # 406print(menu.get("poha", "not on menu"))7 8order = ["dosa", "vada", "dosa"]9bill = 010for dish in order:11    bill += menu.get(dish, 0)12print(f"Total: Rs {bill}")  # Total: Rs 16013 14for dish, price in menu.items():15    print(f"{dish:<6} Rs {price}")16 17student = {"name": "Kabir", "marks": {"maths": 91, "physics": 84}}18print(student["marks"]["maths"])   # 91

1/6Curly braces with key: value pairs create a dict.

A canteen menu as a dict: add, update, look up safely, total a bill and read nested data.

Save yourself the pain

Common mistakes

Oops

Using d['key'] for data that may not have that key, and crashing with KeyError.

Do this instead

Use d.get('key') or check 'key' in d first.

Oops

Looking for a value with 'Rs 60' in menu.

Do this instead

in checks keys, not values. Use 60 in menu.values() to search values.

Oops

Adding or deleting keys while looping over the same dict.

Do this instead

Loop over list(d.keys()) or build a new dict, otherwise Python raises RuntimeError.

Your mission

Word counter

~20 min

Quick check

prices = {'tea': 15}. What does prices.get('coffee') return?

Go deeper

  1. 1Store a student's name, roll number and marks in a dict.
  2. 2Use d.get('key', default) instead of d['key'] when the key may be missing.
  3. 3Count how often each word appears in a sentence using a dict.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge