Keys, Items, and enumerate
Lesson 18 of 48 in Coddy's Python for PHP Developers course.
PHP foreach ($data as $key => $value) provides pairs. Python for key in data provides dictionary keys; use data.items() for key/value pairs. For positional lists, enumerate(values, start=1) pairs each element with a counter. Changing the start changes labels, not which element is visited. Dictionary iteration follows insertion order; sort keys explicitly when output must be alphabetical.
PHP 8.3
<?php
$data = ['red' => 2];
foreach ($data as $key => $value) { echo $key, ' ', $value, "\n"; }Python
data = {"red": 2}
for key, value in data.items():
print(key, value)Porting trap
Python for key, value in data tries to unpack each key, not a key/value pair. A two-character key can hide that mistake. Do not add or remove dictionary keys while iterating its live view.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler