Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please give an answer by using python. Q2. Write a function that takes two dicti

ID: 3568901 • Letter: P

Question

Please give an answer by using python.

Q2. Write a function that takes two dictionaries (d1 and d2, where keys and values are integers) and returns a new dictionary which the union of items in dl and d2. Union of two dictionaries dl and d2 results in a new dictionary d3 such that: If a key is included only in dl, then this key and corresponding value from dl should be included in d3. If a key is included only in d2, then this key and corresponding value from d2 should be included in d3. If a key is included in both dl and d2, then d3 should include this key and larger Of the corresponding values from dl and d2. Example: If d1={l:2,3:4,5:6} and d2={l:3,6:5,3:8}your output should be something like {l:3,5:6,6:5,3:8}. The order of elements in the output dictionary is not important.

Explanation / Answer


def mergeDictionary(d1,d2):
   d3=d1.copy()
   for x in d2.items():
           if(d3.has_key(x[0])):
               if (d2[x[0]]>d3[x[0]]):
                   d3[x[0]]=d2[x[0]]
           else:
               d3[x[0]]=x[1]
   return d3
  
d1={1:2,3:4,5:6}
d2={1:3,5:6,6:5,3:8}
d3=mergeDictionary(d1,d2)
print "d1->",d1
print "d2->",d2
print "d3->",d3