【问题标题】:Looping through dicitionary in Python在 Python 中循环遍历字典
【发布时间】:2022-09-22 22:38:00
【问题描述】:

我正在从 Eric Matthes 的《Python Crash Course》一书中学习,他的字典循环解决方案并没有像他声称的那样工作。

这是我需要做的:

#looping through dicitionary with names of people and their favorite programming language.
#if name matches one of my friends, we will display a message about their favorite language.
#it prints only Phil. Why???

favorite_languages = {\'jen\': \'python\',\'sarah\': \'c\',\'edward\': \'ruby\',\'phil\': \'python\'}
friend = [\'phil\', \'jen\', \'jakub\']
for name in favorite_languages.keys():
    print(name)

if name in friend:
    print(\" Hi \" + name.title() +
    \", I see your favorite language is \" +
    favorite_languages[name].title() + \"!\")
  • 因为你的缩进是错误的。 if 不在 for 循环中。
  • 从 python 3.6 开始,我建议使用f-strings:尝试print(f\"Hi {name.title()}, I see your favorite language is {favorite_languages[name].title()}!\") 当然在你修复缩进问题之后

标签: python dictionary


【解决方案1】:

您错过了缩进,并且该语句仅适用于 dict 的最后一项。 您需要检查 dict 循环中的每个项目,而不仅仅是最后一个。 解决方案:

favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python'}
    friend = ['phil', 'jen', 'jakub']
    for name in favorite_languages.keys():
        print(name)
        if name in friend:
            print(" Hi " + name.title() +
                  ", I see your favorite language is " +
                  favorite_languages[name].title() + "!")

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2023-04-03
    • 2019-04-24
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多