Dictionary Exercises
Dictionaries will be very useful in the various text problems that we will address. Today's exercises are a mixture of some dictionary basics, plus a couple exercises that serve as a foundation for upcoming bigger exercises.
As always, collaborate with your neighbor and upload your solutions. If you finish early, you can work on your current assignment.
Dictionary basics
-
What does the following do? Try to figure it out yourself before using CodeSkulptor.
ingredients = {} ingredients["bread"] = "1 slice" ingredients["peanut butter"] = "1 ounce" ingredients["jelly"] = "1 ounce" ingredients["bread"] = "2 slices" print ingredients
-
For this set of exercises, we want to use dictionaries that map numbers to numbers. In other words, both the keys and the values are numbers.
-
Define such a dictionary.
-
How can you add up all of the numbers that are keys? Hint: What is the easiest way to get a list of all the keys?
-
How can you add up all of the numbers that are values? Hint: What is the easiest way to get a list of all the values?
-
-
What is wrong with the following dictionary definition?
d = {10 : 4, "good" : "buddy", ["This example"] : ("is", "silly"), ("So", "is") : ["this", "one"]}
More Dictionary Examples
-
Define a function
dict_squares_range(start, stop, step)
. It returns a dictionary such that for each number inrange(start, stop, step)
, the dictionary maps that number to its square.For example,
dict_squares_range(3, 8, 2)
should return{3 : 9, 5 : 25, 7 : 49}
. -
Assume you have a dictionary that maps numbers to numbers, as in the previous two exercises. Use
simpleplot.plot_lines()
to plot the points that this dictionary represents.Read the CodeSkulptor documentation for
simpleplot.plot_lines()
. Note that it allows you to use a dictionary to represent a data set. -
Define a function
print_mapping()
that takes a dictionary. It prints each key/value pair, one per line.For example,
print_mapping({3 : 9, 5 : 25, 7 : 49})
should print the following lines in some order.3 maps to 9 5 maps to 25 7 maps to 49