Map Lookups and KeyError
Lesson 14 of 48 in Coddy's Python for Dart Developers course.
Dart Map lookup returns a nullable value because a key may be absent. Python dict subscripting raises KeyError for a missing key, while get offers an explicit fallback. A present key can hold None, so get alone may not distinguish absence from a stored absence value; membership does. Dart containsKey and Python in check key presence. Ordinary Python dicts preserve insertion order, which is distinct from sorted order. Python keys must be hashable; mutable lists are not valid keys. Do not assume Dart generic key and value types are runtime-enforced by a Python dict annotation.
Dart
void main() {
final counts = <String, int>{'pens': 0};
print(counts['pads']);
print(counts.containsKey('pens'));
print(counts.length);
}Python
counts = {'pens': 0}
print(counts.get('pads', 0))
print('pens' in counts)
print(len(counts))Porting trap
Port a nullable Dart map lookup with care. Decide whether absence means a fallback, an exception, or an explicitly stored None.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler