Menu
CoddyTech

Entries and withIndex

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

Kotlin can destructure map entries in a loop and use withIndex for list positions. Python dictionary iteration yields keys; call items to get key/value pairs. Python enumerate pairs an item with a counter and supports a starting label, unlike simply slicing the list. Keep dictionary structure stable while iterating its live items view.

Kotlin

fun main() {
    val data = mapOf("red" to 2)
    for ((key, value) in data) println("$key $value")
}

Python

data = {"red": 2}
for key, value in data.items():
    print(key, value)

Porting trap

Python for key, value in data attempts to unpack keys themselves. Use data.items() even if a two-character key happens to unpack without an error.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

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

Practice on your own: Online Python compiler