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

python inv dict(d) input: dictionary d representing an invertible function f out

ID: 3886857 • Letter: P

Question

python

inv dict(d) input: dictionary d representing an invertible function f output: dictionary representing the inverse of f, the returned dictionary’s keys are the values of d and its values are the keys of d.


example: given an English-French dictionary
{'thank you': 'merci', 'goodbye': 'au revoir'}
return a French-English dictionary
{'merci':'thank you', 'au revoir':'goodbye'}

>>> inv_dict({'goodbye': 'au revoir', 'thank you': 'merci'}) == {'merci':'thank you', 'au revoir':'goodbye'}

Explanation / Answer

# this code is used to inverse a given dictionary

def inv_dict(d):

   # create new dictionary representing the inverse
   f = {}

   # go through the elements of d:
   for key in d.keys():
       newkey = d[key]
       newvalue = key
       f[newkey] = newvalue

   return f

if __name__ == '__main__':
   print(inv_dict({'goodbye': 'au revoir', 'thank you': 'merci'}) == {'merci':'thank you', 'au revoir':'goodbye'})

-----------------

OUTPUT:

Either go to a terminal and type the following:

$ python3 inversedict.py
True

As you can see the output is True which means the program is correct.

OR, open the python interpreter and type the following:

>>> inv_dict({'goodbye': 'au revoir', 'thank you': 'merci'}) == {'merci':'thank you', 'au revoir':'goodbye'}

True

Again result is True.

NOTE: This code is for python3. If you are using python2, you have to remove the brackets from the print statement. In case of any issues, just leave a comment and I will get back to you.