📚 Reference guide

Dictionaries: Keys, Values, and Lookup

Look up sample status codes by name, loop over the pairs, and print the same data as JSON text.

Series: Python for small scripts

Based on the official Python documentation. Date checked: November 27, 2026. Script tested on Python 3.13.5.

Series: Python for small scripts, Part 6 of 10. Previous: Part 5: Lists: Store and Filter a Set of Items. Next: Part 7: Functions: Write a Reusable Check.

TL;DR

Before you start

The finished script

Save this as codes.py in that folder:

import json

codes = {
    "ok": 200,
    "not_found": 404,
    "error": 500,
}

print(codes["ok"])
print(codes.get("timeout", "unknown"))

for name, code in codes.items():
    print(f"{name}: {code}")

print(json.dumps(codes, indent=2))

When you run it, you should see:

200
unknown
ok: 200
not_found: 404
error: 500
{
  "ok": 200,
  "not_found": 404,
  "error": 500
}

Steps

  1. Save and run the script. Change into python-scripts and run python3 codes.py. Why: you can see a direct lookup, a missing-key lookup, a loop, and a JSON listing in one output. You should see: the block above.
  2. Read the dictionary and the two lookups. "ok", "not_found", and "error" are keys. codes["ok"] returns 200. codes.get("timeout", "unknown") returns the fallback "unknown" because "timeout" is not a key. Why: square brackets raise an error when the key is missing. .get() is the safer choice when a key may be absent.
  3. Read the .items() loop. Each pass sets name to a key and code to its value. Since Python 3.7, a dictionary keeps insertion order, so the lines print in the same order you wrote the keys. Why: this is the usual way to walk both the names and the values.
  4. Read the JSON line. json.dumps builds a text version of the dictionary. indent=2 adds line breaks and spaces so the text is easier to read. Why: configuration files and many HTTP APIs use this shape. The json module is in the standard library, so you do not install anything in this part.

If it fails

Traceback (most recent call last):
  File "keyerror.py", line 2, in <module>
    print(codes["timeout"])
          ~~~~~^^^^^^^^^^^
KeyError: 'timeout'

Use codes.get("timeout", "unknown") when the key may be missing, or check if "timeout" in codes: first.

Stay safe

Next

Part 7: Functions: Write a Reusable Check

Sources

Spot something wrong or outdated? Leave a comment below. Every comment is reviewed to keep these posts accurate.

By commenting, you agree to our Terms of use and confirm this is your own work. Short quotes are fine with a credit and link. Copied, unsafe, or abusive comments are removed. See something copied? Email [email protected].