easy +8 pts

Replace keys with a mapping

Transform dictionary keys using a mapping, preserving values and handling collisions.

Write a function `replace_keys(d, mapping)` that takes a dictionary `d` and a dictionary `mapping` where each key in `mapping` is a key that exists in `d` and maps to a new key name (a string). The function should return a NEW dictionary where every key of `d` is replaced by its mapped value if present in `mapping`, otherwise the key remains unchanged. If two different original keys map to the same new key, the later key in the original insertion order should overwrite the earlier one. The original dictionary `d` must not be modified.

Constraints

The input dictionaries can be empty. Keys are strings. The mapping keys are guaranteed to exist in `d`. Complexity: O(n) time and O(n) space where n is the number of keys in `d`.

Example

>>> replace_keys({'a': 1, 'b': 2, 'c': 3}, {'a': 'x', 'c': 'z'})
{'x': 1, 'b': 2, 'z': 3}
>>> replace_keys({'a': 1, 'b': 2}, {'a': 'b', 'b': 'a'})
{'b': 1, 'a': 2}
>>> replace_keys({}, {})
{}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Create a new empty dictionary.
Iterate over the original dictionary's items.
For each key, use mapping.get(key, key) to get the replacement key.
Assign the value to the new key in the result dictionary.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.