lesson
45 min

Dictionaries and JSON

Store records with labeled fields, and read JSON, the format most public data APIs send.

Objective

By the end of this lesson, you can build a dictionary, read values by key, and turn JSON text into Python data you can loop over.

Dictionaries

A dictionary stores values by label instead of by position. Each label is a key.

county = {"name": "Example County", "state": "TX", "population": 52000}
print(county["population"])

A list of dictionaries is a small table. Each dictionary is a row. Each key is a column.

JSON

JSON (JavaScript Object Notation) is plain text that looks almost exactly like Python dictionaries and lists. When you ask a public data API for data, it usually answers in JSON. Python's built-in json module turns that text into dictionaries.

This JSON is a made-up sample shaped like a county data response. Run it. Then add a fourth county with a population of 75000 and run again.
Python 3
Ctrl+Enter to run | Tab to indent | Python runs in your browser via Pyodide

json.loads means "load from string." The result is a list of dictionaries.

A national example

Judgment check

Averages and totals can hide people. In the example, county B's high broadband rate would pull up a combined average, even though county A is far behind. When you summarize, also look at the rows that fall below a line. That is where help is often needed.

Reflection

Private. Saved only in this browser. No one else can see it.

Ask. Answer. Build together.