Indexes and Dict Iteration
Lesson 18 of 48 in Coddy's Python for JavaScript Developers course.
Keep a position beside each value and unpack dictionary entries without manually synchronizing separate lists.
JavaScript
const stock = {pen: 4, pad: 2};
for (const [name, count] of Object.entries(stock)) {
console.log(name, count);
}Python
stock = {"pen": 4, "pad": 2}
for name, count in stock.items():
print(name, count)What changes
Both examples print pen 4 followed by pad 2. A plain Python dictionary loop yields keys. Calling items() supplies pairs that the loop header unpacks into a key and its value. Dictionaries retain insertion order, although that does not make their ordering rules identical to JavaScript objects for every kind of key. For a sequence, enumerate(values) yields pairs of zero-based index and value. Supply start=1 for human-facing numbering without changing how list indexing works. For example, the first pair from enumerate(["red"], start=1) contains 1 and "red".
Common mistake
Do not remove dictionary keys while iterating its live entries. Build a fresh dictionary containing the entries you want to keep. Likewise, deleting list elements during traversal can shift positions and skip work. Updating an existing dictionary value is different from changing the dictionary size.
Your task
Number observations and count repeated labels in first-seen order. The scaffold supplies the list of labels.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler