Menu
CoddyTech

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

Practice on your own: Online Python compiler