Items and enumerate
Lesson 18 of 48 in Coddy's Python for GDScript Developers course.
GDScript dictionary loops commonly visit keys and look up each value. Python dictionaries also iterate keys by default, and items supplies key/value pairs directly. enumerate labels sequence elements with a counter and can start numbering at one without skipping the first item. Do not change dictionary size while iterating its live view.
GDScript
extends SceneTree
func _init():
var data = {"red": 2}
for key in data:
prints(key, data[key])
quit()Python
data = {"red": 2}
for key, value in data.items():
print(key, value)Porting trap
Python for key, value in data tries to unpack each key rather than each entry. A two-character key can make that mistake appear to work while producing wrong data.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler