Record Filter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- 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.
Some records belong. Others do not.
Example 1
Input:
records = [{"age":30,"name":"Alice"},{"age":25,"name":"Bob"},{"age":30,"name":"Carol"}], criteria = {"age":30}Output:
[{"age":30,"name":"Alice"},{"age":30,"name":"Carol"}]Example 2
Input:
records = [], criteria = {"x":1}Output:
[]
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
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 resultCommon 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.)