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 trialEdward A. Polanco Murillo
2,872 PointsIterating 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():
print(pets)
print(item)
Andrew Fellenz
12,170 PointsHey 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:
print(value)
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():
print(key)
print(value)
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
Edward A. Polanco Murillo
2,872 PointsGot it! thanks again @youssef khouda didn't know it was something that simple.
Edward A. Polanco Murillo
2,872 Points@ Andrew Fellenz Now I fully get how it works now thanks again for your feedback.
youssef b10ta
Courses Plus Student 2,755 Pointsyoussef b10ta
Courses Plus Student 2,755 Pointspets.items()
its items no item and if you want to loop through the vaules and keys in a dic you could use this
i hope this would help you