# Record Filter

> Some records belong. Others do not.

Canonical URL: <https://datadriven.io/problems/record_filter>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list of records (dicts) and a criteria dict, return the records where every key in criteria has a matching value in the record.

## Worked solution and explanation

### Why this problem exists in real interviews

Filtering records by multi-field criteria tests **dict comparison** and whether you can check all key-value conditions without over-engineering. It is the Python equivalent of a SQL WHERE clause with AND conditions.

---

### Break down the requirements

#### Step 1: For each record, check all criteria

Every key-value pair in the criteria dict must match the corresponding field in the record.

#### Step 2: Include the record only if all criteria match

If any criterion fails, skip the record.

---

### The solution

**Multi-field filter with all-match check**

```python
def filter_records(records, criteria):
    result = []
    for record in records:
        matches = True
        for key in criteria:
            if record.get(key) != criteria[key]:
                matches = False
                break
        if matches:
            result.append(record)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n * c) where n is the number of records and c is the number of criteria keys.
> 
> **Space:** O(k) where k is the number of matching records.

> **Interviewers Watch For**
>
> Using `record.get(key)` instead of `record[key]` to handle records that may be missing a criteria key. A missing key should not match.

> **Common Pitfall**
>
> Using `record[key]` which raises KeyError if the key is not in the record. Use `.get()` for safe access.

---

## Common follow-up questions

- What if criteria should support inequality operators? _(Tests building a mini query engine with operator dispatch.)_
- How would you add OR logic between criteria groups? _(Tests accepting a list of criteria dicts where any group matching suffices.)_
- What if records are very large and criteria touch only a few fields? _(Tests indexing: build a hash index on criteria fields for O(1) lookup per record.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/record_filter)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.