Keys, Null, and get
Lesson 14 of 48 in Coddy's Python for PHP Developers course.
Python dictionaries preserve insertion order, like PHP arrays, but their key rules differ. PHP converts some numeric string keys to integers. Python keeps "1" and 1 distinct. Python dictionary lookup with square brackets raises KeyError when absent. get(key, default) supplies a default without inserting; it still returns None for a present key containing None. PHP ?? also falls back for a null value. Membership with in checks keys, not values.
PHP 8.3
<?php
$data = ['x' => null];
echo $data['x'] ?? 7, "\n";
echo count($data), "\n";Python
data = {"x": None}
print(data.get("x", 7))
print(len(data))Porting trap
Do not port $data["x"] ?? 7 to data.get("x", 7) if a present null value must trigger the fallback too. Decide separately whether missing and None should share behavior.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler