python - 如何遍历字典?
问题描述
我目前正在研究循环字典和循环 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)
解决方案
我知道你想要什么:你的逻辑几乎是正确的,但你根本还没有学会如何访问 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)
推荐阅读
- vba - 从手动制作的 Excel 表单自动填充多行
- jasper-reports - 如何仅删除报告数据 Jasper HTML 视图之间的额外空白?
- angular - IntelliJ“未使用的变量”角度
- java - IntelliJ IDEA 社区 + Java 11
- c# - 通过套接字发送 UDP 广播会不断引发异常
- android - 尺寸大小 = driver.manage().window().getSize() 在 android 设备上不起作用
- java - 如何处理未使用的@Override 方法?
- javascript - threejs 线跟随几何
- tcl - 访问在不同命名空间中打开的文件处理程序
- proxy - CNTLM 代理和 .pac 文件