Answer:
- def merge_dict(d1, d2):
- for key in d2:
- if key in d1:
- d1[key] += d2[key]
- else:
- d1[key] = d2[key]
-
- return d1
-
-
- d1 = {
- 'a': 5,
- 'b': 8,
- 'c': 9
- }
-
- d2 = {
- 'c': 5,
- 'd': 10,
- 'e': 12
- }
-
- modified_dict = merge_dict(d1, d2)
- print(modified_dict)
Explanation:
Firstly, create a function <em>merge_dict()</em> with two parameters,<em> d1, d2</em> as required by the question (Line 1)
Since our aim is to join the <em>d2</em> into<em> d1</em>, we should traverse the key of <em>d2</em>. To do so, use a for loop to traverse the <em>d2</em> key (Line 2).
While traversing the d2 key, we need to handle two possible cases, 1) d2 key appears in d1, 2) d2 key doesn't appears in d1. Therefore, we create if and else statement (Line 3 & 5).
To handle the first case, we add the values of d2 key into d1 (Line 4). For second case, we add the d2 key as the new key to d1 (Line 6).
Next, we can create two sample dictionaries (Line 11 - 20) and invoke the function to examine the output. We shall get the output as follows:
{'a': 5, 'b': 8, 'c': 14, 'd': 10, 'e': 12}