Homework 1.2: Reverse lookup (20 pts)¶
a) Looking up a value given the key of a dictionary is syntactically simple, val = d[key]
to find the value corresponding to key
in dictionary d
. In Python, a reverse lookup, in which you are given a value and want to find the corresponding key(s) is not so syntactically simple and is furthermore slow compared to a lookup. Explain why.
b) Your task in part (c) is to write a function that performs a reverse lookup. It should take two arguments, a dictionary and a value, and return a list of all keys that have the value. Do you think the function should raise an exception if the value is not found in the dictionary, or should it instead return an empty list? There is no right answer to this question; you should just explain why you might want one or the other.
c) Now it’s time to write the function. Use principles of test-driven development to do so. You must include all of your tests with your submission. (I know this is due just two days after the lecture on test driven development, so you should save this part of the homework for last.)