smartyfy.mrindigi.com

Python Master Course V2 — 043. Nested Dictionaries

SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 05 · LESSON 043/200

Nested Dictionaries — Hierarchical Data Modelling

Study: 75–100 minutes · Prerequisite: Lesson 042 — Dictionary Methods.

Video lesson

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

Learning outcomes

  • Represent hierarchical information with dictionaries containing dictionaries.
  • Access nested keys safely and distinguish missing keys from missing records.
  • Iterate through nested mappings and calculate grouped totals.
  • Validate record schemas before using values.
  • Build a multi-office financial reconciliation report.

Detailed explanation

A nested dictionary stores structured records under named keys. For example, a top-level key can represent an office and its value can be another mapping of balances, inventory or contact information. This structure is useful when the relationships are hierarchical and direct lookup by key matters.

To retrieve a nested value, use successive key lookups such as offices["A"]["cash"]. This raises KeyError if either required key is absent. Use .get() when missing values are expected, but do not silently replace required business data with zero unless the business rule explicitly permits that assumption.

Nested dictionaries are mutable. A shallow copy duplicates only the outer mapping; nested records may remain shared. Use explicit construction or copy.deepcopy when independent nested records are required.

Understand Nested Dictionaries

A missing account is not a zero balance

The nested model already separates office, source and account. Add one more distinction to the reconciliation contract: an account present with amount zero is a known observation, while an absent account is incomplete information. Subtract amounts only after establishing that both account keys exist. Taking the union of keys prevents omission, but it does not by itself preserve this distinction when get(account, 0) is used.

Python
expected = {"cash": 0, "stock": 10, "fees": 5}
actual = {"stock": 8, "fees": 7, "extra": 0}
for account in sorted(expected.keys() | actual.keys()):
    if account not in actual:
        print(account, "missing_actual")
    elif account not in expected:
        print(account, "unexpected_actual")
    else:
        difference = actual[account] - expected[account]
        if difference != 0:
            print(account, "variance", difference)
Expected output
cash missing_actual
extra unexpected_actual
fees variance 2
stock variance -2

This trace exposes two kinds of findings. Cash and extra need investigation because one side is absent, even though the available amount is zero. Fees and stock are comparable numeric variances. Their signed sum is zero, but the sum of absolute differences is four; the accounts do not match. Do not invent numeric variances for missing-side records unless the business contract expressly treats absence as zero.

Validate one layer at a time

For each office, first require an expected mapping and an actual mapping. Then validate account names and amount types inside each. A missing office is also a structural finding, including an office whose known account mapping is empty. For synthetic integer examples, define amounts as nonnegative integer units. A later money implementation should use finite Decimal values and an explicit currency/rounding policy, rather than mixing binary floats, integers and strings without explanation.

A shallow outer copy is enough when replacing whole office records without editing their contents. It is insufficient when the operation changes a nested amount, because the inner record is still shared. Prefer constructing a new report containing findings rather than modifying the input records. This keeps expected and actual evidence available for review. Use a deep copy only when independent nested mutable structures are genuinely required; it is not a substitute for understanding who owns each object.

Progressive runnable examples

Setup: Python 3.10 or later, standard library only. Save each example separately and run with python filename.py. The following outputs are expected outputs.

Example 1 — Nested lookup

offices = {
    "A": {"cash": 100, "stock": 4},
    "B": {"cash": 80, "stock": 2}
}
print(offices["A"]["cash"])
print(offices["B"]["stock"])
100
2

Example 2 — Grouped totals

offices = {
    "A": {"cash": 100},
    "B": {"cash": 80},
    "C": {"cash": 20}
}
print(sum(record["cash"] for record in offices.values()))
200

Example 3 — Optional lookup

offices = {"A": {"cash": 100}}
print(offices.get("B"))
print(offices.get("A", {}).get("cash"))
None
100

Example 4 — Shallow versus deep copy

from copy import deepcopy
original = {"A": {"cash": 100}}
shallow = original.copy()
deep = deepcopy(original)
shallow["A"]["cash"] = 50
print(original["A"]["cash"])
print(deep["A"]["cash"])
50
100

Professional project — Multi-office cash reconciliation

All amounts below are synthetic nonnegative integer training units. This combined office record stores expected and actual account mappings separately. An absent side is an office-level finding; an absent account is incomplete information, including when the known amount is zero. Only observed amounts on both sides have numeric variances.

offices = {
    "Office A": {
        "expected": {"SB": 1000, "RD": 500},
        "actual": {"SB": 980, "RD": 520}
    },
    "Office B": {
        "expected": {"SB": 700, "RD": 300},
        "actual": {"SB": 700, "RD": 290}
    }
}

def reconcile(records):
    if not isinstance(records, dict):
        raise TypeError("records must be a dictionary")
    for office, data in records.items():
        if not isinstance(office, str) or not office.strip():
            raise ValueError("office must be nonempty text")
        if not isinstance(data, dict):
            raise TypeError("office record must be a dictionary")
        for source in ("expected", "actual"):
            if source not in data:
                continue
            if not isinstance(data[source], dict):
                raise TypeError("account mapping must be a dictionary")
            for account, amount in data[source].items():
                if not isinstance(account, str) or not account.strip():
                    raise ValueError("account must be nonempty text")
                if type(amount) is not int or amount < 0:
                    raise ValueError("amount must be a nonnegative integer unit")
    report = []
    for office in sorted(records):
        data = records[office]
        if "actual" not in data:
            report.append((office, None, "missing_office", None))
            continue
        if "expected" not in data:
            report.append((office, None, "unexpected_office", None))
            continue
        expected, actual = data["expected"], data["actual"]
        for account in sorted(expected.keys() | actual.keys()):
            if account not in actual:
                report.append((office, account, "missing_actual", None))
            elif account not in expected:
                report.append((office, account, "unexpected_actual", None))
            elif actual[account] != expected[account]:
                report.append((office, account, "variance", actual[account] - expected[account]))
    return report

for finding in reconcile(offices):
    print(finding)

assert reconcile({"A": {"expected": {"cash": 0}, "actual": {}}}) == [("A", "cash", "missing_actual", None)]
assert reconcile({"A": {"expected": {}, "actual": {"cash": 0}}}) == [("A", "cash", "unexpected_actual", None)]
assert reconcile({"A": {"expected": {"cash": 0}, "actual": {"cash": 0}}}) == []
assert reconcile({"A": {"expected": {}}}) == [("A", None, "missing_office", None)]

Expected output:

('Office A', 'RD', 'variance', 20)
('Office A', 'SB', 'variance', -20)
('Office B', 'RD', 'variance', -10)

Walkthrough: Each report tuple is (office, account, status, difference). Missing office sides use None for account; every missing-side finding uses None for difference. Exact matches add no finding. Sorted names make output deterministic. The assertions exercise zero versus absence and a missing office observation; passing assertions print nothing.

Extra project: Extend the contract to finite nonnegative Decimal amounts with an explicit currency and rounding policy. Export findings as CSV; report status counts separately from signed and absolute numeric variance totals. Test missing offices, missing accounts, exact matches, offsetting discrepancies, and rejected input. Keep both inputs unchanged.

Common mistakes and professional practices

  • Accessing nested keys without checking required schema fields.
  • Using get(key, 0) where missing data should be treated as an error.
  • Assuming a shallow copy isolates nested dictionaries.
  • Comparing only aggregate totals and missing offsetting discrepancies.
  • Mutating records while iterating without planning for structural changes.

Exercises and model answers

  1. Read Office A’s SB expected amount. Answer: offices["Office A"]["expected"]["SB"].
  2. Why use a union of account keys? Answer: to include accounts present in either source.
  3. What does a shallow copy preserve? Answer: references to nested mutable objects.
  4. How do you create an independent nested copy? Answer: deepcopy(original) when appropriate.
  5. Challenge: calculate absolute variance. Answer: sum abs(difference) only for report tuples whose status is "variance"; missing-side differences remain None.

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 actual.get("cash", 0) unsafe when expected cash is zero?

Answer and reasoning:

It makes an absent actual observation indistinguishable from a recorded zero. Check "cash" in actual first, and report missing_actual if it is false.

2. Trace offices["A"]["expected"]["cash"].

Answer and reasoning:

The first lookup selects office A. The second selects its expected account mapping. The third selects cash. Each bracket lookup can raise KeyError independently, so the schema must specify all three levels.

3. What does a shallow copy share?

Answer and reasoning:

Python
original = {"A": {"cash": 10}}
copy = original.copy()
copy["A"]["cash"] = 4
print(original["A"]["cash"])
Expected output
4

The outer dictionaries differ, but both A values refer to the same inner dictionary. Replacing copy["A"] entirely would instead change only the copy’s outer entry.

4. Do variances +20 and −20 mean the accounts reconcile?

Answer and reasoning:

No. Net variance is 0, but absolute variance is 40 and two accounts differ. Report the per-account findings; aggregate totals answer a different question.

5. Which three tests catch the absent-versus-zero bug?

Answer and reasoning:

Compare {"cash": 0} with {} and require missing_actual. Reverse them and require unexpected_actual. Compare {"cash": 0} with itself and require a match. These cases hold the number constant while changing whether the record exists.

Five-question knowledge check

  1. What is a nested dictionary? A. Dictionary containing dictionaries B. String C. Set D. Tuple. Answer: A. Nested mappings represent hierarchical records.
  2. What happens for a missing required key using brackets? A. None B. KeyError C. False D. Zero. Answer: B. Direct key lookup raises KeyError.
  3. Does dict.copy deep-copy nested records? A. Yes B. No C. Always D. Only strings. Answer: B. It copies only the outer dictionary.
  4. Why compare all account keys? A. Hide records B. Include missing-side accounts C. Speed printing D. Change amounts. Answer: B. Union prevents omitted keys.
  5. What does a zero net difference prove? A. All accounts match B. No discrepancies C. Nothing about per-account equality D. No records. Answer: C. Positive and negative discrepancies can cancel.

Mastery checkpoint

Explain nested lookup, safe access, shallow versus deep copying, and the reconciliation algorithm. Add at least three tests, including missing keys and offsetting differences.

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