# The Dict Comparator

> Two dictionaries. Subtle differences.

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

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given dicts d1 and d2, return a dict containing every key from d1 whose value differs from d2[key] (including keys missing in d2). Values come from d1. Return the dict directly.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **dict comparison and diff computation**, a pattern used in configuration auditing, schema migration, and data reconciliation. It probes set operations on dict keys and value comparison.

---

### Break down the requirements

#### Step 1: Find keys in dict1 that differ from dict2

A key qualifies if it exists in dict1 but is either missing from dict2 or has a different value.

#### Step 2: Collect qualifying entries

Build a result dict with these keys mapped to their dict1 values.

#### Step 3: Sort keys in the output

Return a dict with sorted keys for deterministic output.

---

### The solution

**Key-by-key diff with sorted output**

```python
def dict_diff(dict1: dict, dict2: dict) -> dict:
    result = {}
    for key in dict1:
        if key not in dict2 or dict1[key] != dict2[key]:
            result[key] = dict1[key]
    sorted_result = {}
    for key in sorted(result.keys()):
        sorted_result[key] = result[key]
    return sorted_result
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) due to sorting, where n is the number of qualifying keys.
> 
> **Space:** O(n) for the output dict.

> **Interviewers Watch For**
>
> Whether you handle both cases: key missing from dict2, and key present but with a different value. Missing either case produces an incomplete diff.

> **Common Pitfall**
>
> Including keys that are in dict2 but not in dict1. The problem only asks for entries from dict1.

---

## Common follow-up questions

- How would you produce a symmetric diff (changes in both directions)? _(Tests combining diffs from dict1-dict2 and dict2-dict1.)_
- What if values are nested dicts? _(Tests recursive deep comparison.)_
- How would you report what changed (old value vs new)? _(Tests returning tuples of (old, new) instead of just the dict1 value.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_dict_comparator)
- [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.