Menu
CoddyTech

Mappings and Lookup Loops

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

C has no built-in dictionary: an array search or a chosen map library must define key matching, storage, and ownership. Python dict maps hashable keys to values. Membership tests keys regardless of the stored value. Indexing a missing key raises KeyError; get returns a default without inserting the key. Dictionaries preserve insertion order, which is different from sorted order. Use brackets for runtime keys, not attribute syntax: counts.pens does not access this mapping.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int main(void) {
    const char *names[] = {"pens", "pads"}; int counts[] = {0, 4};
    for (int i = 0; i < 2; ++i) {
        if (strcmp(names[i], "pens") == 0) printf("present %d\n", counts[i]);
    }
    return 0;
}

Python: complete example.py

counts = {"pens": 0, "pads": 4}
print("pens" in counts, counts.get("pens", 9))

Watch the difference

A zero count remains a present key. Checking bool(counts.get(key)) confuses present zero with absence. Python strings are immutable and hashable, so they are ordinary dictionary keys.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

Read nonnegative pen and pad counts, followed by a requested key that may be empty or unknown. Build a dictionary with exactly pens and pads. Print the requested key's membership boolean, then its count or zero when absent. A present zero must still yield True.

Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.

Replace a C key-search loop with dictionary membership, not a truth test of the count.

Your code goes in main.py. The locked driver.py is the entry file, supplies execution and checks, 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 C Developers

Practice on your own: Online Python compiler