Menu
CoddyTech

each_pair and enumerate

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

Ruby Hash iteration supplies key/value pairs to a block. Iterating a Python dictionary directly supplies keys only; call items() to get pairs for unpacking. Ruby each_with_index supplies value then index and counts from zero. Python enumerate supplies index then value and can start the counter at one. Changing the counter start does not skip an element. Use these tools when output needs labels as well as values. Avoid adding or removing dictionary keys while iterating its live view. If you need to change keys, iterate a separate snapshot or construct a new dictionary.

Ruby

{'red' => 2}.each { |key, value| puts "#{key} #{value}" }
['red'].each_with_index { |value, index| puts "#{index} #{value}" }

Python

counts = {'red': 2}
for key, value in counts.items():
    print(key, value)
for index, value in enumerate(['red'], start=1):
    print(index, value)

Porting trap

A Python loop written as for key, value in counts tries to unpack each key itself. A two-character key can accidentally appear to work while yielding characters instead of a stored value.

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

Practice on your own: Online Python compiler