Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Dart Developers

Practice on your own: Online Python compiler