Named Lists and Dictionaries
Lesson 14 of 48 in Coddy's Python for R Developers course.
R named lists can store records, while environments provide mutable name-to-value lookup with reference semantics. Python dict is an insertion-ordered mapping with hashable keys. Missing dict subscripts raise KeyError; get supplies an explicit fallback without insertion. A missing named-list extraction can yield NULL, so distinguish the target's absent-key behavior. R lists may have duplicate names and some access forms permit partial matching; Python dictionary keys are unique and string lookup is exact. Use membership to distinguish an absent key from an existing zero or None. Explicitly sort keys when the task needs sorted output rather than insertion order.
R
counts <- list(pens=0)
cat(is.null(counts[["pads"]]), "\n", sep="")
cat("pens" %in% names(counts), "\n", sep="")Python
counts = {'pens': 0}
print(counts.get('pads', 0))
print('pens' in counts)
print(len(counts))Porting trap
Do not assume a partial field abbreviation accepted by an R access form will match a Python dictionary key.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler