Challenge 11: Merge Two Dictionaries (Safely)

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

  1. a and b must both be dictionaries.
    • If either input is not a dictionary, raise a TypeError.
  2. If both dictionaries contain the same key, the value from b overrides the value from a.
  3. 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 a or b.
  • Keep your behavior explicit for overlapping keys.

Python Challenge 11 Solution Merge two dictionaries safely

Python Challenge 11 Test Merge two dictionaries safely

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" or prefer="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.