Ask Question
14 November, 17:00

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

+1
Answers (1)
  1. 14 November, 17:19
    0
    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 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}
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a Python function merge_dict that takes two dictionaries (d1, d2) as parameters, and returns a modified dictionary (d1) constructed ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers