Dictionary Lookup and Order
Lesson 14 of 48 in Coddy's Python for Swift Developers course.
Swift Dictionary subscripting normally returns an optional; Python d[key] raises KeyError when absent. Python get returns a default without insertion. Python dictionaries preserve insertion order, but do not sort keys; Swift Dictionary does not promise the same insertion-order contract. Use membership to distinguish a missing key from a present zero or None. Python dict values can be None without deleting the key, unlike assigning nil through a simple Swift dictionary subscript.
Swift example
let counts = ["pens": 0]
print(counts["pens"] != nil)
print(counts["pads"] ?? 0)Python
counts = {"pens": 0}
print("pens" in counts)
print(counts.get("pads", 0))Porting trap
When accumulating, assign the updated value explicitly. A Python get fallback does not create the missing entry.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerRead integer counts for pens and pads, then a requested key, on three lines. Counts are nonnegative. Create a dictionary with those two keys. Print whether the requested key exists, then its count with a default of 0 for an absent key. The request can be any string, including empty. A present count of zero must still report True.
Print only the requested output, with a newline after each line. Keep the supplied input scaffold. No loops or functions are needed.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler