首页 > 解决方案 > 如何遍历字典?

问题描述

我目前正在研究循环字典和循环 Python。字典里面是对他们最喜欢的语言及其结果进行民意调查的人。参与者列表显示必须参加的人;一些人已经采取了,而其他人没有。

我想遍历Participants列表,如果他们在字典中,它会打印出他们已经完成了投票,打印出他们的名字,并打印出他们最喜欢的语言。如果没有,它会打印出他们需要完成投票,然后是他们的名字。

Poll = {
'Jen': 'Python',
'James': 'C++',
'John': 'Java',
}

Participants = ['Jade', 'Jen', 'James', 'Josh', 'John']

for Participant in Participants:
    if Participant, Language in Poll.items():
        print("Poll completed, " + Participant + '.' +
        'Favorite language: ' + Language)
    else:
        print('Please complete the poll, ' + Participant)

标签: pythondictionaryconditional-statements

解决方案


我知道你想要什么:你的逻辑几乎是正确的,但你根本还没有学会如何访问 dict 特征......但你已经接近了。

您无法比较语言是否在 Poll.items() 中——这是您从 .items() 中提取的内容Poll。您需要更多练习变量的工作原理。相反,您只询问此人是否在Poll; 如果是这样,您提取语言:

for Participant in Participants:
    if Participant in Poll:
        print("Poll completed, " + Participant + '.' +
        'Favorite language: ' + Poll[Participant])
    else:
        print('Please complete the poll, ' + Participant)

推荐阅读