HashMap to dict
Lesson 14 of 48 in Coddy's Python for Rust Developers course.
Python dict maps hashable keys to values and preserves insertion order. Rust HashMap does not promise that iteration order; BTreeMap orders by key. Python d[key] raises KeyError if missing. Python d.get(key, default) returns the default without inserting, similar to a Rust borrowed lookup followed by a fallback. Use key in d for membership even if the stored value is zero. Python keys need compatible equality and hashing, rather than explicit Rust Eq + Hash bounds.
Rust excerpt inside main
use std::collections::HashMap;
let counts = HashMap::from([("pens", 0)]);
println!("{}", counts.contains_key("pens"));
println!("{}", counts.get("pads").copied().unwrap_or(0));Python
counts = {"pens": 0}
print("pens" in counts)
print(counts.get("pads", 0))Porting trap
Rust entry APIs can insert on demand. Python get is only a lookup; assign a new value explicitly when accumulating counts.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler