Reputation: 13
I'm very new to programming so bare with me.
I'm learning through a book "Python Crash Course: A hands-on, project-based Introduction to Programming"
I'm writing a code that involves making a dictionary, followed by looping a sentence about the items in the dictionary, then creating a loop that just prints the value of each key in the dictionary.
I got the first part done, however when writing the second loop it simply returns the value of the last key in the dictionary and loops it over multiple times instead of looping the individual values in the key. Can anyone tell me what I'm doing wrong?
Here is the code:
rivers = {'nile': 'egypt', 'amazon': 'south america',
'mississipi': 'us', 'yangtze': 'china',
'ganges': 'india',}
for river, rivers in rivers.items():
print(f"The {river.title()} is in {rivers.title()}")
for river in rivers:
print(rivers)
Upvotes: 0
Views: 148
Reputation: 81594
You are rebinding the name rivers
from the entire dictionary to an individual value in each iteration. After the first loop is done, rivers
will point out to the last visited value in the dictionary.
You should be using a different name for one of the references. What about country
per each value during the iteration?
rivers = {'nile': 'egypt', 'amazon': 'south america',
'mississipi': 'us', 'yangtze': 'china',
'ganges': 'india',}
for river, country in rivers.items():
print(f"The {river.title()} is in {country.title()}")
for river in rivers:
print(rivers)
However, I'm still not sure what is the purpose of the second loop. If you want to print the key, value pairs alone that can be done with the first loop.
for river, country in rivers.items():
...
print(river, country)
Upvotes: 3