为什么我的 if 语句函数只将我的打印消息分配给 python 中字典中的最后一个键值

why does my if statement function only assign my print message to the last key-value in my dictionary in python

favorite_languges = {
"John": "Python",
"Aisha": "C",
"Newton": "maths",
"Budon": "C++",
}

# for loop to print all keys

for name in favorite_languges.keys():
    print(name.title())

# for loop to print message to all users in the friends list

friends = ['Budon', 'Aisha']
if name in friends:
    language = favorite_languges[name].title()
    print(f'\t{name.title()}, i see you love {language}')

我正在尝试将消息 print(f'\t{name.title()}, i see you love {language}') 打印给好友列表和字典中的用户,但它只将其分配给字典中的最后一个键值

我试着 运行 每行一次,但我似乎找不到出路。我才练了3个月

您没有在第二个循环中使用 for 循环。所以你需要添加它。还有一件事:你应该检查一个名字是否在字典中,否则你会得到一个 KeyError 一个未知的名字。

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C++", }

for name in favorite_languges.keys():
    print(name.title())

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C++", }

for name in favorite_languges.keys():
    print(name.title())


friends = ['Budon', 'Aisha']
for name in friends:
    if name in favorite_languges:
        language = favorite_languges[name].title()
        print(f'\t{name.title()}, i see you love {language}')
    else:
        print(f"No information about {name}")

预期输出:

John
Aisha
Newton
Budon
John
Aisha
Newton
Budon
    Budon, i see you love C++
    Aisha, i see you love C

有可能你只是 运行 for 循环结束后的 if 语句,这意味着它总是在数组的最后一个点,试试这样:

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C++"}
friends = ['Budon', 'Aisha']
for name in favorite_languges.keys():
    print(name.title())
    if name in friends:
        language = favorite_languges[name].title()
        print(f'\t{name.title()}, i see you love {language}')