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

Abdullah Al-Romaihi
Abdullah Al-Romaihi
2,172 Points

How is this done...can't find the answer on google nor did I get it from the videos

I want to know what's the solution been on it for a while now What is entered in the blank below..

Complete this code so that it will iterate over all the key:value pairs in the student dictionary.

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

for key, val in student. _____():
    print(key)
    print(value)

2 Answers

Hi!

I'll try to break this down for you, maybe it helps! Python dictionaries have keys and values. For example, in the dictionary student provided in the exercise, 'name' is the key and 'Craig' is the value. So it's a key-value pair. Each key has a value.

If you wish to iterate over all the keys and get only the keys, this is what you do:

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

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

"""
OUTPUT:
name
major
credits
"""

If you wish to iterate over all the values and get only the values, this is what you do:

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

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

"""
OUTPUT:
Craig
Computer Science
36
"""

And if you need to iterate over all the key:value pairs (just like in the exercise) and get both of them, this is what you do:

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

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

"""
OUTPUT:
name
Craig
major
Computer Science
credits
36
"""
daniel104729
daniel104729
7,171 Points

https://docs.python.org/3/tutorial/datastructures.html#dictionaries it is Python's documentation on dictionaries, it contains the answer I have checked though it is in a later section on the same page. One thing I think is important to learn is how to read documentation, it is a skill that a lot of people fail to learn and use. I know I have asked questions when I should have just looked at the documentation/manual. Best of luck