2. This is KEY! Help (A Day at the Supermarket)


The exercise is to print out the definitions. However, when I enter this code:

for webster in {
	"Aardvark" : "A star of a popular children's cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
     print webster

Only the keys get printed but the system accepts my answer. Why? Also, how do I edit the code such that the definitions are printed?

Thank you!


Uhh you should probably use the variable that already refers to the dict, instead of creating a whole new dict to iterate through.

As for your question, value types define how to iterate through its instances (a dictionary is an instance of the dict class) and iterating through a dict produces its keys one at a time. You can get key-value tuples by iterating through dict.items() (creates a list) or dict.iteritems() (creates an iterator)

some_dict = {'hi': 5, 'there': 3}
for key, value in some_dict.iteritems():
    print '%r: %r' % (key, value)


'there': 3
'hi': 5

Or since it's a dict, you can use the keys to get the items

When more than one variable is specified in the for-loop, Python will unpack the values into them. This is the same as:

a, b = 3, 5
print a, b # 3, 5

And the %r's means to use repr when converting to string (all values have to be converted to string in order to print them), repr is an alternative to str, repr is more developer-oriented, note how the output includes the quotes around the strings, if %s was used, those would have been omitted.