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?”.
Looking things up
Square brackets raise KeyError when the key is absent. .get() returns None instead — or a
default you choose:
Changing a dictionary
Keys are unique. Assigning to an existing key replaces its value — and a literal with a repeated key simply keeps the last one:
Iterating
Dictionaries keep insertion order, so what you put in first comes out first. Sorting works
through sorted on the items:
Dictionaries of dictionaries
Real data nests. This is exactly the shape of a JSON API response:
Building dictionaries
Counting things
Counting occurrences is so common that the standard library has a tool for it:
Try it yourself
Print the total number of tokens used across all three calls, as total: N.
Build fast_enough: a dictionary of only the models with latency under 100 ms. Use a dict comprehension.
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 aforloop most of the time.- Nested dictionaries are exactly how JSON and API responses are shaped.
Counterandd.get(k, 0) + 1are the two ways to count things.