Maps, Keys, and Ordering
Lesson 14 of 48 in Coddy's Python for C++ Developers course.
Python dict maps hashable keys to values and preserves insertion order. std::map visits keys in comparator order, while unordered_map does not promise insertion order. Python d[key] raises KeyError when missing. C++ map operator[] inserts a default-constructed value, so a read can change its size. Python d.get(key, default) returns a fallback without inserting. key in d tests membership even when the value is zero or None.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
std::map<std::string, int> counts{{"pens", 0}};
std::cout << counts.count("pens") << '\n';
std::cout << counts["pads"] << '\n' << counts.size() << '\n';Python
counts = {"pens": 0}
print("pens" in counts)
print(counts.get("pads", 0))Porting trap
Do not assume Python iteration is sorted because a C++ map was sorted. Use sorted(d) when output must follow key order.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler