smartyfy.mrindigi.com

Python Master Course V2 — 048. Complex Data Structures

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

Complex Data Structures

Estimated study: 75–100 minutes · Prerequisite: Lesson 047 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 complex data structures.
  • 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

Combining dictionaries, lists and tuples models structured real-world records. Document schemas and validate required fields at each nesting level.

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 Complex Data Structures

Let each container do one job

Real records often need several container types together. A list represents a sequence of orders; a dictionary names fields in one order; a list inside the order holds its line items; a tuple can represent a fixed pair of product name and quantity. This is useful composition, not complexity for its own sake. The best structure makes the questions your program asks easy to express and makes invalid arrangements obvious.

Define the schema before calculating totals. In this lesson, each order is a dictionary with an integer id and a required items list. Each item is a two-element tuple containing a nonempty product name and a positive integer quantity. An empty items list is allowed and means the order has no lines. A missing items field means the record is malformed. The two cases must not be collapsed with an automatic empty-list default.

Python
orders = [
    {"id": 101, "items": [("Pen", 2), ("Book", 1)]},
    {"id": 102, "items": [("Pen", 3)]},
]
print(orders[0]["id"])
print(orders[0]["items"][1][0])
print(orders[1]["items"][0][1])
Expected output
101
Book
3

Trace each bracket operation separately. orders[0] selects the first order dictionary. The items key selects its list of lines. Index 1 selects the second tuple, and index 0 selects that tuple’s product name. A list index can raise IndexError, a dictionary key can raise KeyError, and an unexpected intermediate type can cause TypeError. Knowing the expected type at each step tells you what to inspect when a traceback points to a long nested expression.

Aggregate without modifying the evidence

Python
orders = [{"id": 101, "items": [("Pen", 2), ("Book", 1)]},
          {"id": 102, "items": [("Pen", 3)]}]
totals = {}
for order in orders:
    for name, quantity in order["items"]:
        if not isinstance(name, str) or not name.strip():
            raise ValueError("product name must be nonempty text")
        if type(quantity) is not int or quantity <= 0:
            raise ValueError("quantity must be a positive integer")
        totals[name] = totals.get(name, 0) + quantity
print(totals)
print(orders[0]["items"])
Expected output
{'Pen': 5, 'Book': 1}
[('Pen', 2), ('Book', 1)]

The outer loop visits orders, and the inner loop visits their lines. Tuple unpacking gives each field a descriptive name, avoiding repeated numeric indexing. The result dictionary is newly created; the order data is read but never edited. The type check deliberately rejects booleans because True behaves like the integer 1 in many numeric operations. Positive whole quantities are the declared contract, so zero, negatives and fractional quantities are rejected rather than silently rounded.

Validate structure before entering the calculation

The example assumes each order has the stated outer structure. A full importer should first require dictionaries, verify the id and items fields, ensure items is a list, and ensure every line has exactly two fields before unpacking. Report an error with the order ID and line position so the source can be repaired. Do not catch every exception and substitute zero; that conceals malformed evidence as a legitimate total.

Test two orders sharing a product, an empty order list, an order with an empty items list, a missing items key, and an invalid quantity. Decide whether product spelling is exact or normalized before grouping: Pen and pen are otherwise different keys. The total amount of work follows the number of orders plus the total number of line items, not the square of the order count. Nested syntax alone does not imply quadratic processing.

Runnable example

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

orders=[{"id":1,"items":[("Pen",2),("Book",1)]}]
print(orders[0]["id"])
print(orders[0]["items"][0])

Expected output:

1
('Pen', 2)

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 — Complex Data Structures in practice

Build a reusable Python function for a realistic record-processing workflow. Keep the calculation separate from user interaction and make output deterministic. The complete function below validates the stated order and item schema before aggregation, includes order and line context in errors, groups exact product spellings, and preserves its inputs.

def product_totals(orders):
    if not isinstance(orders, list):
        raise TypeError("orders must be a list")
    for position, order in enumerate(orders, start=1):
        if not isinstance(order, dict):
            raise TypeError(f"Order {position}: record must be a dictionary")
        if "id" not in order or type(order["id"]) is not int:
            raise ValueError(f"Order {position}: id must be an integer")
        if "items" not in order or not isinstance(order["items"], list):
            raise ValueError(f"Order {order['id']}: items must be a supplied list")
        for line, item in enumerate(order["items"], start=1):
            context = f"Order {order['id']}, line {line}"
            if not isinstance(item, tuple) or len(item) != 2:
                raise ValueError(f"{context}: item must be a two-field tuple")
            name, quantity = item
            if not isinstance(name, str) or not name.strip():
                raise ValueError(f"{context}: product name must be nonempty text")
            if type(quantity) is not int or quantity <= 0:
                raise ValueError(f"{context}: quantity must be a positive integer")
    totals = {}
    for order in orders:
        for name, quantity in order["items"]:
            totals[name] = totals.get(name, 0) + quantity
    return totals

sample = [{"id": 1, "items": [("Pen", 2)]},
          {"id": 2, "items": [("Pen", 3), ("Book", 1)]}]
print(product_totals(sample))
assert product_totals([]) == {}
assert product_totals([{"id": 3, "items": []}]) == {}
assert sample[0]["items"] == [("Pen", 2)]

Expected output:

{'Pen': 5, 'Book': 1}

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

Follow one bracket lookup at a time and name the intermediate container type.

1. What does orders[0]["items"][1][0] select in the example?

Answer and reasoning:

The product name Book: first order, its items list, second item tuple, then the first field of that tuple. Write the intermediate types as dict, list, tuple, str to check the path.

2. Why is an empty items list different from a missing items key?

Answer and reasoning:

An empty list is a supplied record with no line items and contributes nothing. A missing key violates the schema and should be reported. Defaulting both to an empty list hides incomplete records.

3. Why reject quantity=True?

Answer and reasoning:

A boolean is an int subclass, but it does not represent a deliberate quantity in this schema. type(quantity) is int accepts plain integers only and rejects True, 1.5 and “2”. Conversion belongs in a separate input-parsing stage.

4. Will copying only the orders list isolate inner items?

Answer and reasoning:

No. orders.copy() duplicates the outer list but shares order dictionaries and their items lists. Reading them is fine; independently editing nested data requires copying the relevant nested layers or constructing new records.

5. Supply a test that verifies totals and preservation.

Answer and reasoning:

Python — append these checks to the project script
sample = [{"id": 1, "items": [("Pen", 2)]},
          {"id": 2, "items": [("Pen", 3)]}]
assert product_totals(sample) == {"Pen": 5}
assert sample[0]["items"] == [("Pen", 2)]

Use the lesson’s product_totals function after adding the stated validation. The first assertion tests aggregation, and the second checks that the first source record was not modified. Both successful assertions produce no output.

Mastery checkpoint

Explain complex data structures, predict the code output, run the project and create three new tests, including a failure case.

Summary: Combining dictionaries, lists and tuples models structured real-world records. Document schemas and validate required fields at each nesting level.

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