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
BeginnerThe 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler