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 Iterating Over Dictionaries

Iterating this particular step

I am having difficulty figuring out why my code doesn't work. its asking to include the pets.item() but it still giving an error message. I am not sure if I should incorporate the .item() within the second print statement.

pets = {'name':'Ernie', 'animal':'dog', 'breed':'Pug', 'age':2}
for item in pets.item():
youssef b10ta
youssef b10ta
Courses Plus Student 2,755 Points

its items no item and if you want to loop through the vaules and keys in a dic you could use this

pets = {'name':'Ernie', 'animal':'dog', 'breed':'Pug', 'age':2}
for item, pets1 in pets.items():

i hope this would help you

Andrew Fellenz
Andrew Fellenz
12,170 Points

Hey Edward,

Regular lists only contain values, so we can iterate through them with a simple for loop, like in your code above:

for value in pets:

If you were using a list then that would be exactly right.

However, dictionaries have both keys and values. This requires a different loop structure. The correct structure for dictionaries is:

for key, value in pets.items():

In the same way that a regular for loop passes each indexed value to your variable (value, in the first example I gave), the .items() method tells a dictionary to pass each key to the variable before the comma (",") in our for-loop and each value to the variable after the comma. By default, in Python, when you don't call the .items() method, the dictionary only iterates through the keys it contains and not their corresponding values.

I hope that's helpful!

3 Answers

Got it! thanks again @youssef khouda didn't know it was something that simple.

@ Andrew Fellenz Now I fully get how it works now thanks again for your feedback.