We covered everything you need to know about dictionaries over the last two lectures. Today we do some exercises to practice using them.
You should have already read Chapter 9 on Dictionaries.
Solutions can be viewed here.
Write a function squareme(cakes) that takes one dictionary argument, a mapping from types of cakes (string) to how many we have (int). This function squares each value. The function does not return, but simply changes the dictionary's values. Below is an example of an expected dictionary:
{'bundt':4, 'genoise':2, 'chiffon':6, 'red velvet':3}
Write a function read_alphas(filename) that takes one string argument, a filename, and creates a dictionary based on the file's contents. The function returns that dictionary. Its keys are alpha codes and its values are last names. Each line of the file looks like this:
Chambers,m258745,Annapolis,MD
Write a function find_chambers(alphas) that takes one dictionary argument from the above read_alphas(filename) function (keys are alphas -- values are last names), and returns a list of all alphas with the last name 'Chambers'.
Write a function sum_values(d) that takes one dictionary argument which has string keys and float values, and it returns the sum of all the values.
Write a function pretty_print(d) that takes one dictionary argument, and it prints the contents of the dictionary in sorted key order, one key/value per line like so:
key val key2 val2 key3 val3 ...
Write a function duplicate(d) that takes one dictionary argument, and returns a new dictionary that is an exact copy.
You can actually copy a dictionary by just doing the following, but we want you to do this exercise anyway:
copy = original.copy()