Dictionaries and Records
Lesson 14 of 48 in Coddy's Python for JavaScript Developers course.
Store named values in a dictionary and distinguish a missing key from a stored false value.
JavaScript
const stock = new Map([["pens", 0]]);
console.log(stock.has("pens"));
console.log(stock.get("pads"));
console.log(stock.get("pens"));Python
stock = {"pens": 0}
print("pens" in stock)
print(stock.get("pads"))
print(stock["pens"])What changes
Both mappings contain a zero count for pens. The printed existence flags use different capitalization, and a missing lookup prints undefined in JavaScript versus None in Python. A dictionary maps keys to values. Square-bracket access reads a required key and raises KeyError if it is absent. mapping.get(key, default) returns the stored value when present and the default only when absent. Omitting the default uses None. Assigning mapping[key] = value inserts or updates a key. key in mapping tests keys, not values. Keys are case-sensitive when they are strings.
Common mistake
A dictionary is not a JavaScript object literal with its prototypes removed. Keys are dictionary entries rather than attributes, so use stock["pens"], not stock.pens. Python keys must be hashable, which excludes lists and dictionaries; JavaScript Map can use object identities as keys. A stored zero or None does not make a key absent.
Your task
Build a stock dictionary and report key presence separately from its count. This lets an unknown item and an out-of-stock item both have count zero without losing their difference.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler