Merge Data with Comprehension and Generator in Python

Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

37 lines
Python 3.9+
def merge_data(users, orders):
    """
    Merge user and order data using a dictionary comprehension
    and a generator expression for filtering.
    """
    # Build a lookup: user_id -> user name
    user_map = {user["id"]: user["name"] for user in users}

    # Generator: yield orders with user names attached
    merged = (
        {
            "order_id": order["id"],
            "user_name": user_map.get(order["user_id"], "Unknown"),
            "total": order["total"],
        }
        for order in orders
        if order["total"] > 50
    )

    return list(merged)


if __name__ == "__main__":
    users = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
        {"id": 3, "name": "Charlie"},
    ]
    orders = [
        {"id": 101, "user_id": 1, "total": 75.5},
        {"id": 102, "user_id": 2, "total": 20.0},
        {"id": 103, "user_id": 3, "total": 99.9},
        {"id": 104, "user_id": 99, "total": 60.0},
    ]

    result = merge_data(users, orders)
    print(result)

Output

stdout
[{'order_id': 101, 'user_name': 'Alice', 'total': 75.5}, {'order_id': 103, 'user_name': 'Charlie', 'total': 99.9}, {'order_id': 104, 'user_name': 'Unknown', 'total': 60.0}]

How it works

The dictionary comprehension user_map builds a fast lookup from user IDs to names, so merging is efficient even with many users. The generator expression lazily iterates over orders, filtering those with total > 50 and attaching the user name via user_map.get(). The .get() method safely returns 'Unknown' for missing user IDs, avoiding a KeyError. Converting the generator to a list with list(merged) materializes the results only when needed. The function is generic — it works with any list of dictionaries that have the expected keys.

Common mistakes

  • Using `user_map[order['user_id']]` instead of `.get()` causes a KeyError for unknown users.
  • Forgetting to filter by `total > 50` or filtering with incorrect variable names.
  • Wrapping the generator in list() unnecessarily inside the function when you could return the generator itself.

Variations

  1. Use a list comprehension instead of a generator, returning a list directly if memory is not a concern.
  2. Use `defaultdict` from `collections` to avoid 'Unknown' handling in some cases.

Real-world use cases

  • Combining user profile data with recent transactions for a dashboard view in a web app.
  • Preprocessing API responses by joining related entities before saving to a database.
  • Filtering and transforming event logs by user attributes in an ETL pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.