Run a for loop to iterate dictionary values


#1



Hi. I am trying to use a for loop to iterate the values in a dictionary but can't seem to get it right. I can get it to return the keys, but not the values.


https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/2/1#


I tried this...

for bonus in residents:
    print bonus

but this returns all the keys, not the values.

Then I tried the following but it gives me an error.

for bonus in residents:
    print bonus[]

"error: invalid syntax (python, line 9)"

It seems like I need some code for print all but not sure what that would be. I realize Codecademy might not accept it as a passing this lesson which I've already done, but I'm just trying to multiple ways here.


Replace this line with your code.


#2

bonus now contains the keys, so then you can do:

dictionaryName[keyName]

so how would this look in your specific code?


#3

If I use

print residents["Sloth"]
print residents["Burmese Python"]

It returns the values of 105 and 106 respectively which is what the assignments wants.

But, what I'm trying to do is use a for loop so I don't have to call each key individually to get the value (Sloth and Burmese Python). If this list had many more items, and I only wanted to look at the values, writing
print residents["Each_Animal"]
would be time consuming.

Is there a way to use a for loop to print just the values. Maybe something like

for bonus in residents:
    print bonus[All_values]

#4

look:

x="Sloth"
print residents[x]

we can also use variables to access values from dictionary. This variable could also be an iterator.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.