Quiz 2

593 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Programming in Python · Week 7 — Dictionaries and frequency Deep study for Quiz 2 week 7. Dictionaries map keys to values — ideal for counting, lookup tables, and grouping.

Programming in Python · Week 7 — Dictionaries and frequency

Deep study for Quiz 2 week 7. Dictionaries map keys to values — ideal for counting, lookup tables, and grouping.

Week map

Dict creation → key access → add/update → traversal → frequency counting → get and defaults.

Dictionary notation

  • d = {"a": 1, "b": 2} → mapping from keys to values → keys must be hashable (immutable types).
  • d[key] → lookup value → raises KeyError if key missing.
  • d[key] = value → insert or overwrite.
  • key in d → membership test → True if key exists.
  • len(d) → number of key-value pairs.
Mini-example:
python
scores = {"Ana": 88, "Ben": 92}
scores["Ana"]      # 88
scores["Cal"] = 75 # add new pair

Safe access

  • d.get(key) → returns None if missing (or default: d.get(key, 0)).
  • d.get(key, 0) → frequency pattern starter — return 0 when key unseen.
Mini-example:
python
counts = {}
word = "aba"
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
# counts = {'a': 2, 'b': 1}

Frequency counting pattern

python
freq = {}
for item in data:
    freq[item] = freq.get(item, 0) + 1
Alternative with defaultdict (if allowed) or if item in freq branch.

Traversal

python
for key in d:
    print(key, d[key])

for key, val in d.items():
    print(key, val)
.keys(), .values(), .items() return views of dict contents.

Pattern families

Easy — Lookup and update

Read value by key. Add new key. Check membership with in. Predict KeyError vs get.

Medium — Frequency count

Count occurrences in list or string. Find most common. Report keys with count above threshold.

Hard — Nested dict and grouping

Dict of dicts: d[user][month] = score. Group records by category. Merge counts from two sources.

Worked mini-examples

Example 1 — Basic build.
python
capitals = {}
capitals["India"] = "New Delhi"
capitals["France"] = "Paris"
Example 2 — Frequency.
python
votes = ["yes", "no", "yes", "yes", "no"]
tally = {}
for v in votes:
    tally[v] = tally.get(v, 0) + 1
# {'yes': 3, 'no': 2}
Example 3 — Max frequency key.
python
freq = {"a": 3, "b": 7, "c": 2}
best_key = None
best_val = -1
for k, v in freq.items():
    if v > best_val:
        best_val = v
        best_key = k
# best_key = 'b'
Example 4 — Overwrite.
python
d = {"x": 1}
d["x"] = 10   # overwrite, not duplicate key
# len(d) still 1
Example 5 — Invalid key.
python
# d[1, 2](/courses/deep/notes/1%2C%202) = 5  # TypeError — list not hashable
d[(1, 2)] = 5    # OK — tuple is hashable

Traps

  • Using d[key] when key may be absent — use get or check in first.
  • Lists as keys — not allowed.
  • Assuming dict preserves insertion order in very old Python mental models (3.7+ preserves order, but logic should not depend on order unless stated).
  • freq[key] += 1 on missing key raises error — initialize first.
  • Confusing .keys() with values when iterating.

Diagnostic (try yourself)

  1. What does {"x": 1, "y": 2}["y"] return? What happens for ["z"]?
  2. Count letters in "hello" using get(key, 0) + 1 pattern. What is count of 'l'?
  3. Write one line to check if "admin" is a key in dict users.
  4. After d = {}; d["a"] = 1; d["a"] = 2, what is d and len(d)?
  5. Why does counts[word] = counts[word] + 1 fail on first sighting of word in an empty dict?
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.