Skip to content
Tactiverge

Lists, dictionaries and looping over data

Organise real engineering data in Python: slice and transform lists of sensor readings, describe a component with a dictionary, and loop over tables and grid maps.

Lesson 3 of 6 · 35 min · Self-paced · Free

Why data structures matter

A robot is a data factory. A distance sensor produces a new number every few milliseconds. Each wheel has settings such as a gear ratio and a speed limit. A map of the room might be a grid of hundreds of cells, each free or blocked. Before you can analyse any of this, you need a sensible way to hold it in a program.

You have already met lists and the for loop. This lesson goes further: taking pieces of lists, building new lists from old ones, and a second structure — the dictionary — that stores values under names instead of positions. Together they can represent almost any dataset you will meet in this pathway.

Slicing: taking part of a list

Here are seven temperature readings, one per second. One of them looks odd.

readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]   # °C

print(readings[0:3])      # items 0, 1 and 2
print(readings[-3:])      # the last three
print(readings[::2])      # every second item
print(35.9 in readings)   # is this value in the list?
print(sorted(readings))   # a new, sorted copy

Output:

[20.1, 20.3, 20.2]
[20.4, 20.2, 20.5]
[20.1, 20.2, 20.4, 20.5]
True
[20.1, 20.2, 20.2, 20.3, 20.4, 20.5, 35.9]

A slice readings[start:stop] includes start but stops before stop, just like range. Leaving out a number means "from the beginning" or "to the end". A third number is the step. Slicing always produces a new list and never changes the original.

A trap: two names, one list

Lists can be changed after they are created — you can append, remove or overwrite items. That makes this behaviour important:

readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings        # this does NOT copy the list
cleaned[3] = 20.3         # "fix" the spike
print(readings)

readings = [20.1, 20.3, 20.2, 35.9, 20.4]
cleaned = readings.copy() # a genuine, separate copy
cleaned[3] = 20.3
print(readings)

Output:

[20.1, 20.3, 20.2, 20.3, 20.4]
[20.1, 20.3, 20.2, 35.9, 20.4]

Writing cleaned = readings gives the same list a second name, so changing one changes "both". In the first case the raw data was silently overwritten — exactly the kind of quiet error that ruins an experiment. When you want to keep the original, make a copy with .copy() or a slice readings[:].

Building new lists: comprehensions

A very common job is turning one list into another: converting units, or picking out items that meet a condition. A list comprehension does this in one line. Here, raw counts from a distance sensor's analog-to-digital converter are turned into volts (for this converter, 1023 counts means 3.3 V):

raw_counts = [512, 530, 498, 1023, 505]

volts = [round(c * 3.3 / 1023, 2) for c in raw_counts]
print(volts)

saturated = [i for i, c in enumerate(raw_counts) if c >= 1023]
print("Saturated at indices:", saturated)

Output:

[1.65, 1.71, 1.61, 3.3, 1.63]
Saturated at indices: [3]

Read the first comprehension aloud: "round(c × 3.3 / 1023) for each c in raw_counts". The second adds an if to keep only some items. A reading stuck at the maximum count usually means the signal went off the top of the scale, so it is worth flagging rather than trusting.

Walking two lists together, and sliding windows

zip pairs up items from two lists, which is ideal when two sensors were sampled at the same moments. For a two-wheeled robot, the difference between the wheel speeds tells you whether it is driving straight:

left = [100, 102, 98, 101]    # mm/s
right = [100, 110, 120, 101]  # mm/s
print([r - l for l, r in zip(left, right)])

Output:

[0, 8, 22, 0]

A positive difference means the right wheel is faster, so the robot is turning left.

Sometimes each output depends on a group of neighbouring inputs. A moving average replaces each run of window readings with its mean, smoothing out noise:

readings = [20.1, 20.3, 20.2, 35.9, 20.4, 20.2, 20.5]
window = 3

smoothed = []
for i in range(len(readings) - window + 1):
    chunk = readings[i:i + window]
    smoothed.append(round(sum(chunk) / window, 2))
print(smoothed)

Output:

[20.2, 25.47, 25.5, 25.5, 20.37]

Seven readings give five windows, which is why the loop runs len(readings) - window + 1 times. Notice what happened to the spike: averaging did not remove it, it smeared it across three outputs. Knowing what a method does to unusual data is as important as knowing how to code it.

Dictionaries: values with names

A list is good for many values of the same kind in order. A dictionary (dict) is better when each value has a meaning, such as the settings of one wheel drive. Each entry is a key and a value:

drive = {"name": "left_drive", "max_rpm": 300, "gear_ratio": 30}

print(drive["max_rpm"])                    # look up by key
drive["max_rpm"] = 280                     # change a value
drive["encoder_cpr"] = 12                  # add a new key
print(drive.get("current_limit_a", 2.0))   # missing key: use a default
print("gear_ratio" in drive)               # does the key exist?

for key, value in drive.items():
    print(f"{key:12} = {value}")

Output:

300
2.0
True
name         = left_drive
max_rpm      = 280
gear_ratio   = 30
encoder_cpr  = 12

Asking for a key that does not exist with square brackets, such as drive["current_limit_a"], stops the program with a KeyError. .get(key, default) is the safe alternative when a missing key is normal. Dictionaries remember the order in which keys were added.

Counting with a dictionary

Dictionaries are perfect for counting. Here is a made-up status log from a robot:

log = ["OK", "OK", "LOW_BATTERY", "OK", "STALL", "OK", "STALL"]

counts = {}
for status in log:
    counts[status] = counts.get(status, 0) + 1
print(counts)

Output:

{'OK': 4, 'LOW_BATTERY': 1, 'STALL': 2}

The first time a status appears, .get returns 0, so the count starts at 1.

Tables and grids

Real datasets combine the two structures. A list of dictionaries works like a table, one dictionary per row. Here, two distance sensors were logged together (made-up values), and we regroup the table into a dictionary of lists, one list per sensor:

samples = [
    {"t": 0.0, "sensor": "front", "mm": 412},
    {"t": 0.0, "sensor": "left", "mm": 95},
    {"t": 0.1, "sensor": "front", "mm": 398},
    {"t": 0.1, "sensor": "left", "mm": 97},
    {"t": 0.2, "sensor": "front", "mm": 381},
    {"t": 0.2, "sensor": "left", "mm": 96},
]

by_sensor = {}
for s in samples:
    name = s["sensor"]
    if name not in by_sensor:
        by_sensor[name] = []
    by_sensor[name].append(s["mm"])

print(by_sensor)
for name, values in by_sensor.items():
    print(f"{name}: closest {min(values)} mm")

Output:

{'front': [412, 398, 381], 'left': [95, 97, 96]}
front: closest 381 mm
left: closest 95 mm

The front distance is shrinking steadily (the robot is approaching something) while the left distance holds near 96 mm (it is following a wall).

A list of lists works like a grid. This is how many robots store a map: 0 for a free cell, 1 for an obstacle. You read a cell with two indices, row first: grid[row][col].

grid = [
    [0, 0, 0, 1, 0],
    [0, 1, 0, 1, 0],
    [0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0],
]

print(grid[1][3])   # row 1, column 3

obstacles = 0
for row in grid:
    for cell in row:
        if cell == 1:
            obstacles += 1
print(f"{len(grid)} x {len(grid[0])} grid, {obstacles} obstacle cells")

for row in grid:
    print("".join("#" if cell == 1 else "." for cell in row))

Output:

1
4 x 5 grid, 5 obstacle cells
...#.
.#.#.
.#...
...#.

A loop inside a loop visits every cell. The last two lines build each row as a string of characters and join them, a quick way to see a map. You will use this grid again when you meet path-planning algorithms.

Recap

  • Slices like values[a:b] take part of a list without changing it; b is excluded.
  • Assigning a list to a second name does not copy it. Use .copy() to protect raw data.
  • Comprehensions build new lists: [f(x) for x in xs if condition].
  • zip walks two lists in step; a sliding window looks at neighbouring items.
  • Dictionaries store values under keys; .get handles missing keys, .items() loops over pairs.
  • Lists of dictionaries act as tables; lists of lists act as grids.

Knowledge check

Check your understanding

  1. 1. Given values = [5, 6, 7, 8, 9], what is values[1:3]?
  2. 2. After a = [1, 2, 3]; b = a; b[0] = 99, what is a?
  3. 3. drive = {"max_rpm": 300}. What does drive.get("gear_ratio", 1) return?
  4. 4. Which structure best represents a map where each cell is free or blocked?
  5. 5. A 3-reading moving average is applied to data containing one large spike. What happens to the spike?

Project

Programming project: a wheel log summary

Make up a list of at least 12 dictionaries, each describing one sample from a two-wheeled robot: a time in seconds, a left wheel speed and a right wheel speed in mm/s. Include a stretch where the robot turns and one sample where a speed is impossible (for example, 5000 mm/s). Label the data as made-up in a comment.

Write a program that:

  1. Builds separate left and right lists using comprehensions.
  2. Uses zip to print, for each sample, whether the robot is going straight, turning left or turning right. Choose and justify a tolerance in a comment.
  3. Counts how many samples fall into each category using a dictionary.
  4. Applies a 3-sample moving average to each wheel's speeds and prints the result, then writes two sentences on what happened to your impossible value.

No hardware is required.

Deliverables

  • A Python 3 file using lists, dictionaries, a comprehension and zip
  • Printed output showing the per-sample classification and the category counts
  • Two or three sentences on how the moving average treated the impossible value

Go further

Lists, dictionaries and looping over data — Computational Engineering — Tactiverge