Records to Dictionaries
Lesson 14 of 48 in Coddy's Python for Lua Developers course.
Lua tables combine sequence and record roles. Python separates lists and dictionaries. Python dictionaries preserve insertion order, but are not automatically sorted by key; ordinary Lua table traversal has no specified key order. Use bracket lookup for Python dictionary keys: dot notation accesses attributes instead. Missing d[key] raises KeyError; get supplies a default without insertion. A key can exist with a zero or None value, so membership is a separate question.
Lua example
local counts = {pens = 0}
print(counts.pens ~= nil)
print(counts.pads or 0)Python
counts = {"pens": 0}
print("pens" in counts)
print(counts.get("pads", 0))Porting trap
Do not port a Lua record access like counts.pens to a Python dictionary attribute. Write counts["pens"].
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler