Menu
CoddyTech

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.size

Python

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Ruby Developers

Practice on your own: Online Python compiler