v9.1.1
Menu

Dictionary Merger

mediumFREELists & DictionariesPython DictionariesPython Foundations

Problem Statement

Merge and manipulate dictionaries.

Background

Python dictionaries support:

  • Access: d[key] or d.get(key, default)
  • Update: d[key] = value or d.update(other_dict)
  • Keys/Values: d.keys(), d.values(), d.items()
  • Merging (Python 3.9+): d1 | d2

Your Task

Write a function merge_dicts(dict1, dict2) that merges two dictionaries.

Merge Rules

  • If a key exists in both, sum the values (if numeric) or concatenate (if strings)
  • Keep unique keys from both dictionaries
  • Keys from dict1 keep their original order; keys found only in dict2 follow, in the order they appear in dict2

Output Format

Return the merged dictionary.

Example

Input
dict1 = {"a": 1, "b": 2, "c": "hello"}, dict2 = {"b": 3, "d": 4, "c": " world"}
Output
{'a': 1, 'b': 5, 'c': 'hello world', 'd': 4}
Reasoning
  • Inputs: two dictionaries mapping string keys to values that are either numbers or strings. dict1 has keys a, b, c; dict2 has keys b, d, c.
  • Keys in only one dictionary pass through untouched: a keeps 11 (only in dict1) and d keeps 44 (only in dict2).
  • Shared numeric key b: the two values are added, 2+3=52 + 3 = 5.
  • Shared string key c: the strings are joined end to end, dict1's first: hello followed by the leading-space string from dict2 gives hello world. The space comes from dict2's value; nothing is inserted between them.
  • Output: {'a': 1, 'b': 5, 'c': 'hello world', 'd': 4}, four keys, the union of both key sets. Notice the order: dict1's keys stay where they were (c is still third even though it was merged), and the key that only dict2 has, d, comes after them. Joining strings is not symmetric, so swapping the arguments would put the space at the front of the joined string instead.

Constraints

  • Values are either numbers (int/float) or strings
  • For numbers, sum them; for strings, concatenate

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.