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)
endPython
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
BeginnerThe 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler