# Dictionary Key Intersection

> Two dictionaries. What do they share?

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

Domain: Python · Difficulty: medium · Seniority: L5

## Problem

Given two dicts d1 and d2, return a new dict containing keys present in BOTH, with values from d1. Return the dict; key ordering should be sorted ascending.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **set operations on dict keys** and whether you can construct a result dict with sorted keys. It is a common pattern in config reconciliation and data diffing.

---

### Break down the requirements

#### Step 1: Find shared keys using set intersection

Convert both key sets and intersect them to find keys present in both dicts.

#### Step 2: Build the result with values from the first dict

For each shared key, take the value from `d1`.

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

The result dict should have keys in sorted order.

---

### The solution

**Set intersection with sorted key construction**

```python
def intersect_dicts(d1, d2):
    shared_keys = set(d1.keys()) & set(d2.keys())
    result = {}
    for key in sorted(shared_keys):
        result[key] = d1[key]
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n + m + k log k) where n and m are the sizes of d1 and d2, and k is the number of shared keys. The intersection is O(min(n, m)) and the sort is O(k log k).
> 
> **Space:** O(k) for the shared keys set and result dict.

> **Interviewers Watch For**
>
> Using `set(d1) & set(d2)` for the intersection rather than nested loops. This demonstrates familiarity with Python set operations and their O(min(n, m)) performance.

> **Common Pitfall**
>
> Forgetting to sort the keys. The prompt specifies sorted order, and Python dicts preserve insertion order since 3.7, so you must insert in sorted order.

---

## Common follow-up questions

- What if you needed the symmetric difference instead? _(Tests using `set(d1) ^ set(d2)` to find keys in one but not both.)_
- How would you merge both dicts, preferring d1 values on conflicts? _(Tests `{**d2, **d1}` or iterating with precedence logic.)_
- What if values should also match for a key to be included? _(Tests adding a value equality check inside the loop.)_

## Related

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