Write a Python function merge_dict that takes two dictionaries(d1, d2) as parameters, and returns a modified dictionary(d1) constructed using the following rules. The rules for addition into the new dictionary are as follows: Add key/value pairs from d2 into d1. If a key from d2 already appears in d1: the new value in d1 is the sum of the values If a key appear

Respuesta :

Answer:

  1. def merge_dict(d1, d2):
  2.    for key in d2:
  3.        if key in d1:
  4.            d1[key] += d2[key]
  5.        else:
  6.            d1[key] = d2[key]
  7.    
  8.    return d1
  9. d1 = {
  10.    'a': 5,
  11.    'b': 8,
  12.    'c': 9  
  13. }
  14. d2 = {
  15.    'c': 5,
  16.    'd': 10,
  17.    'e': 12
  18. }
  19. modified_dict = merge_dict(d1, d2)
  20. print(modified_dict)

Explanation:

Firstly, create a function merge_dict() with two parameters, d1, d2 as required by the question (Line 1)

Since our aim is to join the d2 into d1, we should traverse the key of d2. To do so, use a for loop to traverse the d2 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}