# Rename Keys

> Old names out. New names in.

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

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a record dict and a mapping dict (old_key -> new_key), return a new dict where keys listed in mapping are renamed to their new names. Keys not in the mapping pass through unchanged.

## Worked solution and explanation

### Why this problem exists in real interviews

Renaming dict keys according to a mapping tests **dict transformation** logic. It checks whether you handle the pass-through case (unmapped keys) correctly.

---

### Break down the requirements

#### Step 1: For each key in the record, check if it is in the mapping

If the key is mapped, use the new name. Otherwise, keep the original.

#### Step 2: Build a new dict with renamed keys

Copy each value to the result dict under its (possibly renamed) key.

---

### The solution

**Key remapping with pass-through for unmapped keys**

```python
def rename_keys(record, mapping):
    result = {}
    for key in record:
        new_key = mapping.get(key, key)
        result[new_key] = record[key]
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the number of keys in the record.
> 
> **Space:** O(n) for the new dict.

> **Interviewers Watch For**
>
> Using `mapping.get(key, key)` for the default-to-self pattern. This is a clean one-liner that avoids an if-else branch.

> **Common Pitfall**
>
> Modifying the original dict in place. Renaming a key in place requires deleting the old key and inserting the new one, which is error-prone during iteration.

---

## Common follow-up questions

- What if two original keys map to the same new key? _(Tests conflict detection: raise an error or define last-write-wins behavior.)_
- How would you apply the rename to a list of records? _(Tests wrapping the function in a loop or using map().)_
- What if the mapping is bidirectional and you need to reverse it? _(Tests inverting the mapping dict with `{v: k for k, v in mapping.items()}`.)_

## Related

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