Structured Data and Text

Lesson 53 of 54 · Python Foundations

A collection can hold records, with each dictionary describing a rectangle. Area is width multiplied by height; adding the individual areas gives a total, not the area of a combined outline.

def total_area(rectangles: list[dict[str, int]]) -> int:
    total = 0
    for rectangle in rectangles:
        total += rectangle["width"] * rectangle["height"]
    return total

panels = [{"width": 3, "height": 4}, {"width": 2, "height": 5}]
print(total_area(panels))
print(total_area([]))
22
0

The first area is 12 and the second is 10. This function assumes each dictionary has both keys and nonnegative dimensions in the same unit; absent keys raise KeyError. dict[str, int] does not require particular keys or positive values.

For text, a separator belongs between items, not at either edge. A separate variable tracks what to insert before the next item.

def comma_text(words: list[str]) -> str:
    result = ""
    separator = ""
    for word in words:
        result += separator + word
        separator = ","
    return result

print(comma_text(["red", "blue", "gold"]))
print(repr(comma_text([])))
red,blue,gold
''

Initially the separator is empty, so the first word has no leading comma. After that it is a comma. An empty list returns an empty string, shown with repr so the absence of characters is visible. In ordinary code, ",".join(words) is a concise built-in alternative.