smartyfy.mrindigi.com

Python Master Course V2 — 044. Dictionary Comprehensions

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 05 · LESSON 044/200

Dictionary Comprehensions

Estimated study: 75–100 minutes · Prerequisite: Lesson 043 and earlier collections lessons.

Video lesson

Video not yet available. A dedicated space is reserved for a verified video URL or player.

Learning outcomes

  • Explain the behavior and use cases of dictionary comprehensions.
  • Apply the correct Python syntax and predict output.
  • Handle missing, duplicate and invalid data deliberately.
  • Implement a practical real-world processing project.
  • Write edge-case tests and explain failures.

Detailed explanation

Comprehensions create mappings from iterables using a key:value expression and optional filter; duplicate keys overwrite earlier values.

Begin by defining the expected data types, key constraints, and the output contract. Consider whether the operation creates a new collection or mutates an existing one. For reports, sort results where stable ordering matters. When records represent business data, missing information should be reported rather than silently replaced unless a clear rule permits defaults.

Professional Python code benefits from small functions, descriptive names, explicit validation and repeatable tests. Assess the complexity of nested operations when data volumes grow.

Understand Dictionary Comprehensions

Read a comprehension in execution order

A dictionary comprehension creates a new mapping from an iterable. Its shape is {key_expression: value_expression for item in source if condition}. Although the key/value expressions are written first, read the loop and filter first: take an item, test the condition, then calculate the key and value if it passes. A final if removes entries; it does not put False values into the result.

Python
scores = {"Ana": 80, "Ravi": 45, "Mira": 90}
passed = {name: score + 2 for name, score in scores.items()
          if score >= 60}
print(passed)
print(scores["Ana"])
Expected output
{'Ana': 82, 'Mira': 92}
80

Ana passes using the original score 80, so the result receives 82. Ravi fails the filter and contributes no entry. Mira contributes 92. The original score mapping is unchanged because this comprehension creates a new dictionary and stores immutable integer results. Creating a new outer dictionary does not automatically deep-copy any lists or nested dictionaries used as values; those references can still be shared.

Translate the concise form into a loop

An ordinary loop is the clearest debugging tool for a comprehension. Initialize an empty mapping, loop over the same source, use an if statement, then assign the calculated value. These steps let you print intermediate variables or add validation without cramming many decisions into one expression. Keep a comprehension for a readable transformation or filter, not for printing, mutating unrelated objects, or managing several error branches.

Python
scores = {"Ana": 80, "Ravi": 45, "Mira": 90}
passed = {}
for name, score in scores.items():
    if score >= 60:
        passed[name] = score + 2
print(passed)
Expected output
{'Ana': 82, 'Mira': 92}

Duplicate keys overwrite; they do not accumulate

If two source items produce equal keys, the later value wins. {name: amount for name, amount in rows} is therefore unsuitable for summing repeated offices. The result cannot store two separate entries with the same key. Decide whether repeated names mean “latest value”, “error”, “collect a list” or “add amounts”, and implement that rule explicitly. For a case-insensitive lookup, also consider that different original names may collapse to one normalized key.

Aggregate once, then format the result

Python
rows = iter([("A", 10), ("B", 20), ("A", 5)])
totals = {}
for office, amount in rows:
    totals[office] = totals.get(office, 0) + amount
ordered = {office: totals[office] for office in sorted(totals)}
print(ordered)
print(list(rows))
Expected output
{'A': 15, 'B': 20}
[]

This project reads each input record once, then uses a comprehension only to create a sorted presentation mapping. The iterator returned by iter remembers its progress and is exhausted after the loop, explaining the empty list. A generator behaves similarly; Lesson 101 covers the mechanism in depth. In the original repeated-scan design, collecting office names consumes a one-shot iterator before any sums run. Even for a reusable list, scanning every row once per office wastes work. One-pass accumulation accepts either kind of input and makes the intended addition rule visible.

Test the filter at its boundary: a score just below 60 should disappear, exactly 60 should remain, and an empty source should produce an empty dictionary. This verifies the condition rather than only its most obvious examples.

Runnable example

Setup: Python 3.10+, standard library only. Save the following as lesson_044.py and run python lesson_044.py. The output is expected, not a claim of execution on Smartyfy.

scores={"Ana":80,"Ravi":45,"Mira":90}
passed={name:score for name,score in scores.items() if score>=60}
print(passed)

Expected output:

{'Ana': 80, 'Mira': 90}

Walkthrough: Identify the starting collection, trace each operation and compare the final state with the expected output. Change one input to verify your understanding.

Real-world project — Dictionary Comprehensions in practice

Build a reusable Python function for a realistic record-processing workflow. Keep the calculation separate from user interaction and make output deterministic. This version accepts a one-pass iterable of office/amount pairs, adds repeated-office amounts, and does not modify the records. The assertions compare list and one-shot iterator results.

def grouped_totals(rows):
    totals = {}
    for office, amount in rows:
        totals[office] = totals.get(office, 0) + amount
    return {office: totals[office] for office in sorted(totals)}

sample = [("A", 10), ("B", 20), ("A", 5)]
print(grouped_totals(sample))
assert grouped_totals(iter(sample)) == {"A": 15, "B": 20}
assert grouped_totals([]) == {}

Expected output:

{'A': 15, 'B': 20}

Extra project: Add validation for malformed records, a CSV export, summary totals, and five independent tests. Cover empty data, duplicates, one-sided missing records and large inputs where applicable. Explain how your algorithm’s running time grows with the input size.

Common mistakes and best practices

  • Assuming all required keys and values exist.
  • Confusing ordered and unordered collections.
  • Overwriting duplicate dictionary keys without realizing it.
  • Accidentally mutating shared nested data.
  • Ignoring edge cases or using unsafe defaults for missing business records.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Read the loop and filter first, then calculate the surviving keys and values.

1. What does {n: n*n for n in range(4) if n % 2 == 0} produce?

Answer and reasoning:

Expected output
{0: 0, 2: 4}

Only 0 and 2 pass the even-number filter. Each surviving number becomes a key and its square becomes the value.

2. Does a comprehension with a final if preserve every source key?

Answer and reasoning:

No. The final if selects entries. To preserve every key while choosing different values, put a conditional expression in the value position, such as {n: "even" if n % 2 == 0 else "odd" for n in range(3)}.

3. Predict the result of repeated office keys.

Answer and reasoning:

Python
rows = [("A", 10), ("A", 5)]
print({office: amount for office, amount in rows})
Expected output
{'A': 5}

The second A replaces the first A. No summation occurs. Use an accumulator to obtain 15.

4. Why can the original grouped-totals design fail with a generator?

Answer and reasoning:

Its first traversal consumes the generator while collecting offices. Subsequent traversals find no rows, producing zero sums rather than the real totals. Accumulate once, or explicitly require and materialize a reusable sequence when repeat traversal is essential.

5. Does a new comprehension guarantee independent nested lists?

Answer and reasoning:

Python
source = {"A": [1]}
result = {key: value for key, value in source.items()}
result["A"].append(2)
print(source["A"])
Expected output
[1, 2]

The new mapping stores the same list reference. Use value.copy() for independent flat lists, or deliberate deeper copying when the schema contains further mutable nesting.

Mastery checkpoint

Explain dictionary comprehensions, predict the code output, run the project and create three new tests, including a failure case.

Summary: Comprehensions create mappings from iterables using a key:value expression and optional filter; duplicate keys overwrite earlier values.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.