enumerated to enumerate
Lesson 18 of 48 in Coddy's Python for Swift Developers course.
Swift enumerated yields offsets with elements; Python enumerate does the same and accepts a custom starting counter. That start changes numbering, not where iteration begins. Python dictionary iteration alone yields keys; items yields key/value pairs. For Swift collections with noninteger indexes, an enumerated offset is not necessarily a collection index, while Python list indexing uses integer positions. Avoid changing dictionary size while iterating a live items view.
Swift example
let counts = ["red": 2]
for (key, value) in counts { print(key, value) }
for (index, label) in ["red", "blue"].enumerated() {
print(index + 1, label)
}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
When output requires a key order, sort explicitly instead of assuming a Swift Dictionary traversal order carries into Python.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler