Merging dictionaries is a common task in Python—config files, API payloads, defaults vs. overrides, you name it. This challenge teaches you how to merge two dictionaries predictably, with clear conflict rules and safe input handling.
Your Task
Write a function that merges two dictionaries into a new dictionary.
Function Signature
def merge_dicts(a: dict, b: dict) -> dict:
…
Rules
aandbmust both be dictionaries.- If either input is not a dictionary, raise a
TypeError.
- If either input is not a dictionary, raise a
- If both dictionaries contain the same key, the value from
boverrides the value froma. - Return a new dictionary (do not modify the original inputs).
Examples
merge_dicts({"a": 1}, {"b": 2})
# → {"a": 1, "b": 2}
merge_dicts({"a": 1, "b": 1}, {"b": 2})
# → {"a": 1, "b": 2}
merge_dicts({}, {"x": 10})
# → {"x": 10}
Invalid Input Examples
merge_dicts("a", {"b": 2}) # TypeError
merge_dicts({"a": 1}, None) # TypeError
merge_dicts(["a"], {"b": 2}) # TypeError
Hints (Optional)
- Python offers multiple ways to merge dictionaries.
- Make sure your function does not mutate
aorb. - Keep your behavior explicit for overlapping keys.


What This Challenge Teaches
- Dictionary fundamentals
- Safe input validation
- Conflict resolution rules (override behavior)
- Returning new objects instead of mutating inputs
Bonus Challenges
- Add a parameter
prefer="right"orprefer="left"to control which dict wins - Merge more than two dictionaries
- Deep-merge nested dictionaries (advanced)
🔗 View reference solution on GitHub
(After you’ve tried the challenge)
👉 Next Challenge → Count Items in a List
Want more practical Python challenges?
Subscribe to the Solve With Python newsletter and get new problems delivered to your inbox.