简体   繁体   English

循环遍历字典键中的最后一个值而不是字典中的所有值

[英]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"我正在学习一本书“Python 速成课程:一个动手的、基于项目的编程简介”

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.您正在将整个字典中的名称rivers重新绑定到每次迭代中的单个值。 After the first loop is done, rivers will point out to the last visited value in the dictionary.第一次循环完成后, rivers将指出字典中最后访问的值。

You should be using a different name for one of the references.您应该为其中一个参考使用不同的名称。 What about country per each value during the iteration?迭代期间每个值的country怎么样?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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