Typorithm · easy

Dictionaries, sets and deterministic summaries

pythonscriptingdata-boundariesindependent-practice
Saved on this device
Full lesson · 4 learning steps Open any exercise for focused practice
1

Step 1 of 4 · intro card

Dictionaries, sets and deterministic summaries

0%

Concept and contract

Use keys for counts, membership for uniqueness and an explicit sort for presentation.

A dictionary maps keys to values; a set represents unique members. The worked function counts a list of already normalized country codes and returns both the count mapping and a sorted unique-country list. These are two different views of the same input population.

For UA, US, UA the counts are UA two and US one, and the unique presentation is UA followed by US. A set does not preserve an occurrence count, so replacing the count loop with only a set would lose information the report needs.

Mechanism and worked example

get(key, 0) supplies the initial count without raising for a previously unseen key.

get(key, 0) supplies the initial count without raising for a previously unseen key. The loop increments each observed occurrence. set removes repeated country values, and sorted produces a deliberate deterministic list rather than relying on the iteration order of the set.

Dictionary insertion order is defined in modern Python, but that is not the same as alphabetic order. A report contract can choose sorted keys independently of how input observations arrived. Keys must be hashable; mutable lists cannot directly serve as ordinary dictionary or set keys.

Complete worked example

python

def country_summary(countries):
    counts = {}
    for country in countries:
        counts[country] = counts.get(country, 0) + 1
    return {"counts": counts, "unique": sorted(set(countries))}
Reasoning
Counts retain occurrences while the sorted set exposes distinct country values.

Counterexamples and common mistakes

The counterexample overwrites each count with one, reporting presence instead of frequency.

The counterexample overwrites each count with one, reporting presence instead of frequency. It still produces the correct unique list, so checking only the vocabulary would miss the wrong measure. Test at least one repeated country to verify that counts represent occurrences.

Another mistake returns a raw set as if it were a stable JSON-ready list. The collection is useful internally, but output representation and order remain separate decisions. The lab compares an explicit serialized shape, not whichever order happens to appear in one process.

Counterexample: a plausible but incorrect implementation

python

def country_summary(countries):
    counts = {}
    for country in countries:
        counts[country] = 1
    return {"counts": counts, "unique": sorted(set(countries))}
Reasoning
Presence is not frequency; repeated countries must increment the count.

Independent practice: small Python task

Adapt the summary to normalize each supplied country string with strip and upper before counting.

Adapt the summary to normalize each supplied country string with strip and upper before counting. Predict that ua with spaces and UA become one key with count two. Keep the sorted unique list and leave the input list untouched.

The input domain remains strings; handling arbitrary unknown objects is a later boundary task. First compute the normalized key, then increment its count. Do not normalize only the final displayed list while retaining separate unnormalized count keys behind it.

Step 1: Normalize the current country string. Step 2: Increment its normalized count and sort the resulting keys.

Practice starter: solve before reading the solution

python

def country_summary(countries):
    # Normalize each string before both counting and presentation.
    raise NotImplementedError
Reasoning
Normalize once and reuse the same key for all output measures.
  • Hint 1: Use strip().upper() before indexing counts.
  • Hint 2: Do not normalize only one of the two output views.

Solution, tests and trade-offs

The solution counts normalized keys and derives the unique presentation from those same dictionary keys.

The solution counts normalized keys and derives the unique presentation from those same dictionary keys. This keeps the count mapping and displayed vocabulary consistent. Whitespace-only inputs are not part of this exercise's valid domain; a production code validator would need a separate accepted-code policy.

Acceptance includes repeated normalized forms, a single country and an empty population. The empty result contains an empty mapping and empty list rather than inventing an unknown-country observation. Key normalization is an explicit new practice requirement, not something the worked input contract silently assumed.

Practice solution and acceptance checks

python

def country_summary(countries):
    counts = {}
    for raw in countries:
        country = raw.strip().upper()
        counts[country] = counts.get(country, 0) + 1
    return {"counts": counts, "unique": sorted(counts)}
Reasoning
Normalized count keys and the displayed unique vocabulary agree.

Interview reasoning and next step

In an interview, explain hashable keys, occurrence counts, uniqueness and output order separately.

In an interview, explain hashable keys, occurrence counts, uniqueness and output order separately. Avoid saying that every ordered dictionary or every set automatically implements a business deduplication rule. Equal keys can represent the same normalized value while distinct source identities still matter elsewhere.

The next topic examines iteration itself, including zero-based positions and off-by-one boundaries. Understanding how a loop traverses values makes a count update easier to reason about than treating it as a memorized dictionary idiom.

Optional stretch — after the core task works: Explain why a mutable list cannot be a plain dictionary key while an appropriate tuple can.

Computer practice: https://applydjinn.com/typorithm/python-lab-20261105.zip. Run verify.py with your selected Python interpreter, then complete an exercise and check it with --practice followed by the lesson id. The lab uses only the standard library and disposable local fixtures; it never connects to the production database or company feeds.

Use keys for counts, membership for uniqueness and an explicit sort for presentation.