Find a course

Module 1: The Python Data ToolkitLesson 2 of 1214 min

Python Data Structures for Data Work

Use lists, dictionaries, comprehensions and lists of records to summarize data in plain Python, the foundation that NumPy and pandas speed up.

Step 1 of 13Learn

Data as Python sees it

Before reaching for libraries, it's worth knowing how plain Python represents data, because every library builds on these ideas.

A single column of numbers is naturally a list:

temps = [21.5, 23.0, 19.8, 25.1, 22.4]
sum(temps) / len(temps)    # 22.36
max(temps)                 # 25.1

A single record with named fields is naturally a dictionary:

rental = {"station": "Harbor", "hour": 8, "bikes_out": 14}
rental["bikes_out"]        # 14

A whole table is often a list of dictionaries, one dictionary per row:

rentals = [
    {"station": "Harbor", "hour": 8, "bikes_out": 14},
    {"station": "Market", "hour": 8, "bikes_out": 9},
    {"station": "Harbor", "hour": 9, "bikes_out": 6},
]

This is exactly what you get from reading a CSV file with Python's built-in csv.DictReader, or from parsing a JSON API response. It's also the structure pandas accepts when you write pd.DataFrame(rentals).

A few more structures matter: tuples for fixed groups of values, such as a coordinate (59.91, 10.75); and sets for unique values, such as {r["station"] for r in rentals}, which gives {"Harbor", "Market"}.

Four built-in structures for datalist[14, 9, 6]ordered, changeabledict{"station": "Harbor"}look up by keytuple(40.7, -74.0)fixed recordset{"Harbor", "Park"}unique items

Step 2 of 13Practice · Match the pairs

Match each piece of data to the Python structure that fits it best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Daily step counts for one week
  2. One customer with name, email and city
  3. A table of 500 orders, each with the same fields
  4. The distinct countries that appear in the orders
  5. A fixed latitude and longitude pair

Step 3 of 13Learn

Comprehensions: the data scientist's shorthand

List comprehensions build a new list from an existing one in a single readable line. They combine a loop, an optional filter and a transformation:

prices = [12.0, 8.5, 30.0, 4.25]
with_tax = [p * 1.08 for p in prices]             # transform every item
cheap = [p for p in prices if p < 10]            # keep some items
cheap_with_tax = [p * 1.08 for p in prices if p < 10]

They work on records too:

harbor_counts = [r["bikes_out"] for r in rentals if r["station"] == "Harbor"]
# [14, 6]

Dictionary comprehensions build dictionaries the same way:

names = ["Ana", "Ben", "Chen"]
name_lengths = {n: len(n) for n in names}     # {'Ana': 3, 'Ben': 3, 'Chen': 4}

Reading order: [EXPRESSION for ITEM in SOURCE if CONDITION]. The filter keeps items; the expression decides what goes into the result.

A common pattern is counting with a dictionary:

counts = {}
for r in rentals:
    counts[r["station"]] = counts.get(r["station"], 0) + 1
# {'Harbor': 2, 'Market': 1}

dict.get(key, 0) returns 0 when the key isn't there yet. The standard library's collections.Counter does the same job in one call. In pandas, this whole loop becomes df["station"].value_counts().

Anatomy of a list comprehension[o["total"]for o in ordersif o["total"] > 100]what each item becomesthe loopfilter (optional)

Step 4 of 13Practice · Fill in the blanks

Fill in the blanks

Complete the comprehension so it keeps only orders over 100 and returns their totals: [o["total"] o in orders o["total"] > 100]

Step 5 of 13Practice · Code challenge · Python

Write average_bikes(rentals, station) that returns the average bikes_out for rentals at the given station, rounded to 2 decimal places. If the station has no rentals, return 0.

Real Python, running in a sandbox in your browser.
  • average_bikes([{"station": "Harbor", "bikes_out": 14}, {"station": "Market", "bikes_out": 9}, {"station": "Harbor", "bikes_out": 6}], "Harbor")
  • average_bikes([{"station": "A", "bikes_out": 1}, {"station": "A", "bikes_out": 2}, {"station": "A", "bikes_out": 2}], "A")
  • average_bikes([{"station": "A", "bikes_out": 5}], "Zoo")

Step 6 of 13Learn

Why plain Python isn't enough at scale

Plain Python lists and dictionaries are flexible, but they hit limits on real datasets.

Speed. Each element of a Python list is a full Python object, and a for loop executes interpreter instructions for every item. Summing 10 million numbers in a Python loop typically takes around a second; NumPy does it in a few milliseconds, because it stores raw numbers in one contiguous block of memory and loops in compiled C code.

Memory. A Python float object takes about 24 bytes plus an 8-byte pointer in the list. A NumPy float64 takes 8 bytes. For 10 million values, that's roughly 320 MB versus 80 MB.

Convenience. Grouping, joining, handling missing values, reading many file formats and computing rolling averages all need hand-written loops in plain Python. pandas provides each as one tested method.

That doesn't make plain Python obsolete. It remains the right tool for small data, for orchestration (looping over files, calling APIs), and for logic that doesn't fit neatly into tables. Understanding what a groupby or an average does in plain Python also makes it far easier to read pandas code and debug surprising results, which is why this course keeps practicing both.

Approximate memory per number on 64-bit CPythonPython list of floatsabout 32 bytesNumPy float64 array8 bytesEach list slot holds an 8-byte pointer to a 24-byte float object. Approximate.

Step 7 of 13Practice · Work it out

A dataset has 10 million float values. Stored in a NumPy float64 array, each value takes 8 bytes. About how many megabytes does the array need? (Use 1 MB = 1,000,000 bytes.)

Step 8 of 13Practice · Code challenge · Python

Write count_by(records, key) that returns a dictionary counting how many records have each value of key. For example, counting by "station" might give {"Harbor": 2, "Market": 1}.

Real Python, running in a sandbox in your browser.
  • count_by([{"station": "Harbor"}, {"station": "Market"}, {"station": "Harbor"}], "station")
  • count_by([{"size": "M"}, {"size": "L"}, {"size": "M"}, {"size": "M"}], "size")
  • count_by([], "x")

Step 9 of 13Learn

Reading files with the standard library

Before pandas, Python's standard library already handled the most common data files, and it's still handy for quick scripts or environments where you can't install packages.

The csv module reads comma-separated files. csv.DictReader turns each line into a dictionary keyed by the header row, giving you exactly the list-of-records structure from this lesson:

import csv
with open("rentals.csv", newline="") as f:
    rentals = list(csv.DictReader(f))
rentals[0]   # {'station': 'Harbor', 'hour': '8', 'bikes_out': '14'}

Notice the catch: every value comes back as a string, including '8' and '14'. The csv module doesn't guess types, so you must convert them yourself, for example int(r["bikes_out"]). Forgetting this leads to bugs such as "14" + "6" producing "146", or sorting numbers as text so that "10" comes before "9".

The json module reads JSON files and API responses, and it does keep types: numbers become int or float, true becomes True, and nested objects become nested dictionaries.

pandas automates all of this: pd.read_csv infers a type for each column, which is a big convenience and also the reason to check df.dtypes afterwards, since one stray value can make it guess object.

Step 10 of 13Practice · Choose one

A script reads a CSV with csv.DictReader and sorts rows by r["bikes_out"]. The order comes out as 10, 14, 6, 9. Why?

Step 11 of 13Note

Step 12 of 13Practice · True or false

In a Python list comprehension such as [x * 2 for x in nums if x > 0], the if part filters which items are included, while x * 2 decides what each included item becomes.

Step 13 of 13Practice · Choose one

Given rentals as a list of dictionaries, which expression produces the set of distinct station names?