Menu
CoddyTech

Entries and enumerate

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

Python dictionary iteration alone yields keys; use items() for key/value pairs and values() for values. Rust map iteration produces entry pairs, so a mechanical loop translation may accidentally try to unpack a Python key. Python enumerate combines a counter with each item. Its optional start value changes the displayed counter, not where iteration begins. Rust enumerate begins at zero; adding one when displaying a position is a common equivalent.

Rust excerpt inside main

use std::collections::BTreeMap;
let counts = BTreeMap::from([("red", 2)]);
for (key, value) in &counts { println!("{} {}", key, value); }
for (index, label) in ["red", "blue"].iter().enumerate() {
    println!("{} {}", 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

Do not mutate dictionary size while traversing its live views. Build a list of keys first if later removals are needed.

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

Practice on your own: Online Python compiler