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
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler