Menu
CoddyTech

Indexes and Dictionary Items

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

Track positions and counts while preserving encounter order.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

string[] labels = { "red", "blue" };
for (int i = 0; i < labels.Length; i++)
    Console.WriteLine($"{i + 1} {labels[i]}");

Python

labels = ["red", "blue"]
for position, label in enumerate(labels, start=1):
    print(position, label)

What changes

enumerate pairs a counter with each value without manual indexing. Dict iteration alone gives keys; .items() gives key-value pairs for unpacking, rather than C# KeyValuePair.Key and .Value access. Python dictionaries preserve first insertion order; updating an existing value does not move its key.

Transfer mistake

Do not add or delete dictionary entries while iterating its live view. Build counts first, then traverse items. Do not depend on a .NET dictionary enumeration policy to define Python output order.

Your task

Input is one line of lowercase words separated by spaces, possibly empty. The scaffold splits it into labels. First output each label as position label using one-based positions. Then output counts on its own line and each distinct label as label frequency in first-seen order. An empty line produces only counts.

challenge icon

Challenge

Beginner

Input is one line of lowercase words separated by spaces, possibly empty. The scaffold splits it into labels. First output each label as position label using one-based positions. Then output counts on its own line and each distinct label as label frequency in first-seen order. An empty line produces only counts.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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 C# Developers

Practice on your own: Online Python compiler