Given two maps (dictionaries) where keys are strings and values are integers, merge them into a single map such that values for common keys are summed.
Keys that appear in only one map should retain their original value.
Function Signature
def merge_maps(map1: dict[str, int], map2: dict[str, int]) -> dict[str, int]:
Rules
-
A key that appears in both maps appears once in the result, with the two values added. It stays in the result even when the sum is 0.
-
The result is compared as a map, so the order of its keys does not matter.
Constraints
-
0 <= len(map1), len(map2) <= 10^4
-
Keys are non-empty strings containing only lowercase English letters.
-
-10^9 <= value <= 10^9
for every value in either map.
Examples
Input: map1 = {"a":1,"b":2,"c":3}, map2 = {"b":3,"c":4,"d":5}
Output: {"a":1,"b":5,"c":7,"d":5}
Key "a" appears only in map1 and keeps 1, and key "d" appears only in map2 and keeps 5. Keys "b" and "c" are in both maps, so they become 2 + 3 = 5 and 3 + 4 = 7.
Input: map1 = {"x":10}, map2 = {"y":20}
Output: {"x":10,"y":20}
No key is shared, so the result is the union of the two maps.
Input: map1 = {"k":7,"m":-4}, map2 = {"m":4}
Output: {"k":7,"m":0}
Key "m" is in both maps and its values cancel to 0. It stays in the result with the value 0.