smartyfy.mrindigi.com

Python Master Course V2 — 042. Dictionary Methods

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 042/200

Dictionary Methods

Study: 60–90 minutes · Prerequisite: Lesson 041.

Video

Video not available yet. Reserved position for a verified lesson video URL or player.

Objectives and prerequisites

Learn the syntax and professional use of dictionary methods; predict execution, validate inputs, apply it in a project and diagnose errors. Python 3.10+ is recommended, with the previous lesson completed.

Detailed concepts

Dictionary Methods is a key part of writing reusable, reliable Python. Define the data model or function contract before writing implementation. Consider the expected input types, returned values, mutability, ordering, missing-data behavior and time complexity. Use descriptive names and make each operation’s purpose clear.

When adapting the concept to a larger application, separate input validation from core logic, prefer deterministic behavior, and test both normal and edge cases. Avoid assuming that an example is production-ready without explicit error handling and documentation.

Understand Dictionary Methods

Separate reading, changing and removing

Dictionary methods have different contracts. get(key, default) reads without inserting. update(other) copies incoming key/value pairs into the existing dictionary, replacing values for matching keys. pop(key) both removes an entry and returns its former value. clear() removes every entry. Choose the operation according to the change you intend, rather than assuming every method creates a new dictionary.

The return value is not the same thing as the changed object. update and clear return None. Therefore settings = settings.update(overrides) loses your useful reference by assigning None. Call the method on its own line, then inspect the original variable. By contrast, assigning the return from pop is useful when the removed value must be archived or processed.

Python
settings = {"theme": "light", "size": 12}
result = settings.update({"theme": "dark", "language": "en"})
removed = settings.pop("size")
print(result)
print(removed)
print(settings)
print(settings.pop("missing", "not present"))
Expected output
None
12
{'theme': 'dark', 'language': 'en'}
not present

First update replaces theme and inserts language. Then pop returns 12 while removing size. The final pop has a fallback, so it returns text instead of raising KeyError. A fallback does not insert anything. Omitting that fallback is appropriate when absence indicates a bug. Use a distinct sentinel when the dictionary can legitimately contain the same value as your chosen fallback.

Views stay connected to their dictionary

keys(), values() and items() return views, not independent lists. Items are key/value pairs and fit naturally into for key, value in data.items(). A view reflects later dictionary changes. Convert it to a list when you need a snapshot of the entries at that moment; remember that nested mutable values may still be shared. Views are useful for iteration without first copying every entry.

Python
stock = {"Pen": 3}
keys_view = stock.keys()
keys_snapshot = list(stock)
stock["Book"] = 2
print(list(keys_view))
print(keys_snapshot)
for name, quantity in stock.items():
    print(name, quantity)
Expected output
['Pen', 'Book']
['Pen']
Pen 3
Book 2

Collect removals before applying them

Do not add or delete keys while iterating the live dictionary or its views. Structural changes can raise RuntimeError or otherwise invalidate the intended traversal. For a small cleanup, iterate over list(stock), a separate list of keys, or first collect the keys to remove. Updating a value for an existing key is a different operation, but keeping selection and mutation separate is often clearer to review.

For grouping, setdefault(key, default) returns an existing value or inserts and returns the default when the key is absent. For example, groups.setdefault("A", []).append("Mira") creates the first list and appends the name. Do not reuse one shared list as every group’s default. Choose get for non-mutating reads, setdefault for intentional initialization, and a plain loop when the two-step behavior would be hard to follow.

For a useful boundary check, start with an empty dictionary. Its views are empty, get returns the chosen fallback, and pop without a fallback raises KeyError. These outcomes distinguish accepted absence from a violated requirement.

Runnable example

Save as lesson_042.py and run using python lesson_042.py. Expected output is shown for comparison; it has not been executed in the Smartyfy browser.

d = {"a": 1}
print(d.get("b", 0))
d.update({"b": 2})
print(d.pop("a"))

Expected output:

0
1

Trace each statement, note changes to data or control flow, and explain why the output matches the concept. Change one value and predict the result before rerunning.

Practical project — Dictionary Methods application

Build a reusable function or small program that applies the concept to a realistic data-processing workflow. Keep the interface clear and the output deterministic.

def count(rows):
    result = {}
    for key, value in rows:
        result[key] = result.get(key, 0) + value
    return result

print(count([("A", 2), ("A", 3)]))

Expected output:

{'A': 5}

Extra project: Extend this application with input validation, a second processing rule, a report summary and a minimum of five independent tests. Where relevant, handle empty collections, duplicate records, invalid numbers and unexpected types.

Testing plan: Start with the sample, then test an empty input, one item, duplicates and malformed values. Document whether the function returns a sentinel or raises a meaningful exception.

Common mistakes and professional practices

  • Failing to define the expected input and output contract.
  • Assuming values or keys always exist.
  • Confusing mutation with returning a new object.
  • Ignoring edge cases and complexity.
  • Not testing rejected inputs or exception paths.

Practice and explained answers

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

1. Why is d = d.update({"b": 2}) a bug?

Answer and reasoning:

update changes the dictionary in place and returns None. The assignment then binds d to None. Write d.update({"b": 2}) without the assignment.

2. What is printed after capturing a keys view and adding a key?

Answer and reasoning:

Python
d = {"a": 1}
view = d.keys()
d["b"] = 2
print(list(view))
Expected output
['a', 'b']

The view is dynamic. In contrast, list(d) captured before insertion would remain ["a"].

3. How do get and setdefault differ for a missing key?

Answer and reasoning:

d.get("x", 0) returns 0 without changing d. d.setdefault("x", 0) inserts x with value 0 and returns 0. The same apparent result therefore has different side effects.

4. Remove all zero-quantity entries safely.

Answer and reasoning:

Python
stock = {"Pen": 0, "Book": 2, "Pencil": 0}
for name in list(stock):
    if stock[name] == 0:
        stock.pop(name)
print(stock)
Expected output
{'Book': 2}

The loop walks an independent list of keys. Deleting keys from stock does not change the object being iterated.

5. What does pop("x") do when x is absent?

Answer and reasoning:

It raises KeyError and removes nothing. pop("x", None) instead returns None. Choose a fallback only if missing x is an accepted case; otherwise allowing the exception exposes the broken assumption.

Mastery checkpoint

Explain dictionary methods, predict the code output, adapt the project, and test normal, invalid and boundary cases before advancing.

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