简体   繁体   中英

Loop looping through last value in dictionary key instead of all values in dictionary

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM