Menu
CoddyTech

pairs, ipairs, and items

Lesson 18 of 48 in Coddy's Python for Lua Developers course.

Lua pairs traverses keys and values without a general order guarantee; ipairs follows consecutive integer keys until the first missing one. Python dictionary items yields key/value pairs in insertion order. Iterating a dictionary alone yields keys. Python enumerate produces index/value pairs and can start its counter at one without skipping any data. A Python list with None still has an element at that index, so enumeration does not stop there as ipairs does at a nil gap.

Lua example

local counts = {red = 2}
for key, value in pairs(counts) do print(key .. " " .. value) end
for index, label in ipairs({"red", "blue"}) do
    print(index .. " " .. label)
end

Python

counts = {"red": 2}
for key, value in counts.items():
    print(key, value)
for index, label in enumerate(["red", "blue"], start=1):
    print(index, label)

Porting trap

Do not modify dictionary size during iteration over its live views; collect keys to remove first.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

The single input line contains zero or more lowercase words separated by spaces. The supplied split() scaffold makes labels. Print one line per label as its one-based position, one space, then the label. Then print counts on its own line, followed by each distinct label and its frequency separated by one space, in first-seen order. Empty input prints only counts.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Lua Developers

Practice on your own: Online Python compiler