Python Introducing Dictionaries Iterating and Packing with Dictionaries Recap of Iterating and Packing with Dictionaries

Confused on this "Introducing Dictionaries" Quiz

I do not know how to complete questions 2-3 of this quiz on iterating over dictionaries. Here are the questions. They are both "fill in the blank" only, with the blank coming right after "in student."

  1. Fill in the blank. Complete the code so it will iterate over only the keys in the student dictionary.
student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}

for key in student._():
    print(key)

The underscore is the only space I can edit. I would do this by deleting the parens, and just stating for key in student:. But that's not allowed, so what else can I fill in here?

2. Fill in the blank. Complete the code so it iterates over only the values in the student dictionary.

student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}

for val in student._():
    print(val)

Same thing, only here I'd want to change it to:

for key, val in student.items()
    print(val).

Is it possible to complete this only by filling in the blank? (Which again is the underscore after "in student.") Thanks!

2 Answers

Hi Ben

The thing with dictionaries is that they have key-value pairs.

In here...

student = {'name': 'Craig', 'major': 'Computer Science', 'credits': 36}

...the keys are...

  • name
  • major
  • credits

and the corresponding values are...

  • Craig
  • Computer Science
  • 36

You can iterate over the keys like this:

for key in student.keys():
    print(key)

And you can also iterate over the values:

for value in student.values():
    print(value)

If you wish to iterate over both keys and values, you need to use the word items():

for key, value in student.items():
    print(key)
    print(value)

You stated that you wished to do this:

for key in student:

This syntax is more for lists, for example:

fruits = ['apples', 'oranges', 'bananas']

for fruit in fruits:
    print(fruit)

"""
OUTPUT:

apples
oranges
bananas
"""

If you do this with dictionaries, you only get the keys as output:

fruits = {'apples': 3, 'oranges': 6, 'bananas': 2}

for fruit in fruits:
    print(fruit)

"""
OUTPUT:

apples
oranges
bananas
"""

I guess the above is not entirely wrong but for the sake of clarity I would use keys() here:

for fruit in fruits.keys():
    print(fruit)

Does this make any sense?