Skip to content

Python Foundations·Lesson 6 of 67·beginner

Dictionaries

Key-value mapping — the structure behind JSON, API payloads, model configs and almost every record you will ever handle.


In this lesson · 15 min

  • →Create dictionaries and look values up safely
  • →Add, change and remove entries
  • →Iterate over keys, values and pairs
  • →Nest dictionaries the way real API data is shaped

A dictionary maps keys to values. Where a list answers “what is at position 3?”, a dictionary answers “what is the accuracy?”.

PythonPython not started

Looking things up

PythonPython not started

Square brackets raise KeyError when the key is absent. .get() returns None instead — or a default you choose:

PythonPython not started

Changing a dictionary

PythonPython not started

Keys are unique. Assigning to an existing key replaces its value — and a literal with a repeated key simply keeps the last one:

PythonPython not started

Iterating

PythonPython not started

Dictionaries keep insertion order, so what you put in first comes out first. Sorting works through sorted on the items:

PythonPython not started

Dictionaries of dictionaries

Real data nests. This is exactly the shape of a JSON API response:

PythonPython not started

Building dictionaries

PythonPython not started

Counting things

Counting occurrences is so common that the standard library has a tool for it:

PythonPython not started

Try it yourself

Exercise 1

Print the total number of tokens used across all three calls, as total: N.

Your turnPython not started
Exercise 2

Build fast_enough: a dictionary of only the models with latency under 100 ms. Use a dict comprehension.

Your turnPython not started

Check yourself

config = {'retries': 0}. What does config.get('retries', 3) return?

Recap

  • Dictionaries map unique keys to values and preserve insertion order.
  • d[key] raises on a missing key; d.get(key, default) does not.
  • .items() is what you want in a for loop most of the time.
  • Nested dictionaries are exactly how JSON and API responses are shaped.
  • Counter and d.get(k, 0) + 1 are the two ways to count things.
Next: Sets and tuples →