Menu
CoddyTech

Indexes and Map Entries

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

Use enumerate for Python index/value pairs; its start argument changes the reported counter, not where iteration begins. For dict entries use items(). Iterating a dictionary directly yields keys. Python insertion order makes a first-seen frequency report deterministic, while a Go map range would need an explicit key-order strategy. Updating an existing key does not move it to the end.

Go

Go excerpt inside main; imports: fmt. The verification bundle contains the complete program.

// Inside main:
labels := []string{"pad", "pen", "pad"}
counts := map[string]int{}
for i, label := range labels {
    fmt.Println(i+1, label)
    counts[label]++
}
fmt.Println(counts["pad"])

Python

labels = ["pad", "pen", "pad"]
counts = {}
for i, label in enumerate(labels, start=1):
    print(i, label)
    counts[label] = counts.get(label, 0) + 1
for key, value in counts.items():
    print(key, value)

Porting trap

Go counts[label]++ works for an absent key because reading returns zero. Python counts[label] += 1 raises KeyError for a missing key; initialize it or use get.

challenge icon

Challenge

Beginner

Split the one input line into lowercase labels; it may contain no labels. Print each label with its one-based position, separated by a single space. Then print counts and, for every distinct label in first-seen order, its label and frequency separated by a space. Empty input prints only counts. Python dict iteration preserves insertion order; do not assume the same ordering from Go map range.

Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

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

Practice on your own: Online Python compiler