Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

If given:

some_dict = {
    key1: value1,
    key2: value2,
    key3: value3,
    }

There are three ways to iterate on a somedict:

  • iterate over the keys using dict.keys()
# default method. same as using
#     for key in some_dict:
for key in some_dict.keys():
    print(key)

# output
key1
key2
key3
  • iterate over the values using dict.values()
for value in some_dict.values():
    print(value)

# output
value1
value2
value3
  • iterate over both the keys and values using dict.items()
for key, value in some_dict.items():
    print(key, value)

# output
key1 value1
key2 value2
key3 value3

Post back if you need more help. Good luck!!!