Hash Defaults and Dict Keys
Lesson 14 of 48 in Coddy's Python for Ruby Developers course.
Python dictionaries correspond to Ruby hashes, but an absent subscript raises KeyError instead of returning a hash default. Use d.get(key, fallback) for a non-inserting fallback, or test membership with key in d. Ruby Hash.new(0) has a configured default; ordinary Python dicts have no equivalent constructor default. Both preserve insertion order, which is not sorted order. Ruby symbol and string keys are different keys; Python does not have Ruby's symbol literal syntax, so choose a consistent string-key representation. A stored zero or None is still an entry and must not be confused with a missing key.
Ruby
counts = Hash.new(0)
counts['pens'] = 0
puts counts['pads']
puts counts.key?('pens')
puts counts.sizePython
counts = {'pens': 0}
print(counts.get('pads', 0))
print('pens' in counts)
print(len(counts))Porting trap
Do not port a Ruby symbol-key hash and later look up string keys inconsistently. The exercises specify exact text keys and use explicit membership tests.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler