Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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