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 appears only in d1 or d2, then the new value in d1 is the original value from the dictionary that contained this key. Finally, return d1

Respuesta :

Answer:

# We define the function merg_dict with the two dictionaries d1 and d2 that it #will take.

def merge_dict(d1,d2):

      for key in d2:

               if key in d1:

                   d1[key] = d1[key] + d2[key]

               else:

                   d1[key] = d2[key]  

          return d1

# We define the parameters of the dictionary d1 and d2

d1 = {'a': [1, 2, 3], 'b': [2, 2, 2], 'c': [1,2,3]}

d2 = {'a': [4,4,4], 'c': [3,3,3]}

#Next we call on the function merge_dict

print(merge_dict(d1,d2)

We'll obtain the following as output:

{'a': [1,2,3,4,4,4], 'b': [2,2,2], 'c': [1,2,3,3,3,3]}

ACCESS MORE