logo CodeStepByStep logo

reverse

Language/Type: Python collections dict

Write a function named reverse that accepts a dictionary from integers to strings as a parameter and returns a new dictionary of strings to integers that is the original's "reverse". The reverse of a dictionary is defined here to be a new dictionary that uses the values from the original as its keys and the keys from the original as its values. Since a dictionary's values need not be unique but its keys must be, it is acceptable to have any of the original keys as the value in the result. In other words, if the original dictionary has pairs (k1, v) and (k2, v), the new dictionary must contain either the pair (v, k1) or (v, k2).

For example, for the following dictionary:

{42: 'Marty', 81: 'Sue', 17: 'Ed', 31: 'Dave', 56: 'Ed', 3: 'Marty', 29: 'Ed'}

Your function could return the following new dictionary (the order of the key/value pairs does not matter):

{'Marty': 3, 'Sue': 81, 'Ed': 29, 'Dave': 31}

Do not modify the dictionary passed in as the parameter.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.