Map Lookup and Missing Keys
Lesson 14 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin Map indexing returns a nullable result for an absent key. Python dictionary indexing raises KeyError instead. Use get for an optional lookup and in for presence. Both a missing key and a present None can yield None from Python get without an explicit fallback. A fallback argument to get is used only for absence, not for a stored None. Python dictionaries preserve insertion order; sort explicitly when the contract requires key order.
Kotlin
fun main() {
val data = mapOf("x" to 3)
println(data["missing"])
println(data.size)
}Python
data = {"x": None}
print(data.get("x", 7))
print(len(data))Porting trap
Do not assume Kotlin's nullable lookup behavior for data[key]. Decide whether a missing key is an error or expected before choosing brackets or get.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler