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,754 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.