Menu
CoddyTech

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 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 PHP Developers

Practice on your own: Online Python compiler