Menu
CoddyTech

Dictionary Keys and Values

Lesson 14 of 48 in Coddy's Python for C# Developers course.

Distinguish dictionary key presence from a stored zero value.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

var stock = new System.Collections.Generic.Dictionary<string, int> { ["pen"] = 0 };
Console.WriteLine(stock.ContainsKey("pen"));
Console.WriteLine(stock.TryGetValue("pad", out var count) ? count : 0);

Python

stock = {"pen": 0}
print("pen" in stock)
print(stock.get("pad", 0))

What changes

Python dict corresponds to a key-to-value mapping, not a C# record type. Membership checks keys. Indexing an absent key raises KeyError; get(key, default) returns a fallback without inserting it. Like TryGetValue, separate key presence from whether the stored value is zero. Dict preserves insertion order; sort explicitly when the contract asks for alphabetical order.

Transfer mistake

d.get(key, 0) and key in d answer different questions. Do not use a retrieved zero to decide that a key was absent.

Your task

Read counts for pens and pads, then an arbitrary requested key; the key may be empty. Counts are nonnegative. Build a dictionary with exactly those two keys. Output whether the requested key exists, then its count or 0 when absent. A present zero count must still produce True on the first line.

challenge icon

Challenge

Beginner

Read counts for pens and pads, then an arbitrary requested key; the key may be empty. Counts are nonnegative. Build a dictionary with exactly those two keys. Output whether the requested key exists, then its count or 0 when absent. A present zero count must still produce True on the first line.

Editable implementation files: main.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Use the supplied input contract without prompts. Print only the required lines, each ending in a newline.

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 C# Developers

Practice on your own: Online Python compiler