【问题标题】:How to print correct value for chosen key value in dictionary? (Python)如何为字典中选择的键值打印正确的值? (Python)
【发布时间】:2018-09-21 12:23:05
【问题描述】:

我正在制作一本包含不同人生日的字典(用户通过输入填写)。现在,我还希望用户能够写下他/她刚刚添加的名字之一,然后得到那个人的生日作为回报。问题是它总是返回添加到列表中的最后一个日期,不管用户写了哪个名字。所以说用户已经把这些元素放在:{anna:1.october, paul:3.january}。如果我希望程序打印 Anna 的生日,它会打印“anna 的生日是 3.january”。这就是我的代码的样子(顺便说一句,它大致翻译成英文,所以不要介意潜在的语言错误):

birthdays={}
name= ""
date= ""

while True:
    name= input("Who's birthday would you like to add?:")
    if name.strip() == "done":
        break
    date= input("When is the person's birthday?:")

find= input("\n Type in a name that you've added!:")
for name in birthdays:
    if find == name in birthdays or date in birthdays:
        print(" %s 's birthday is at %s" % (name, date))

我觉得最后 4 行中可能有问题。所有帮助表示赞赏! :)

【问题讨论】:

    标签: python dictionary input key-value


    【解决方案1】:

    首先,在您添加的代码中,我没有看到您将值添加到字典的部分。 之后你可以这样搜索:

    if find in birthdays:
        date = birthdays.get(find)
        print(" %s 's birthday is at %s" % (find, date))
    

    【讨论】:

    • 哦,我的代码好像丢失了一行!中间应该有一行写着“birthdays.update({name:date})。无论如何,谢谢!它成功了:)
    【解决方案2】:

    这是你想要的?但我认为它不完整

    birthdays={}
    name= ""
    date= ""
    
    while True:
        name = input("Who's birthday would you like to add?:")
        if name.strip() == "done":
            break
        date = input("When is the person's birthday?:")
        birthdays[name] = date
    
    find = input("\n Type in a name that you've added!:")
    if find in birthdays:
        print(" {} 's birthday is at {}" .format(find, birthdays.get(find)))
    

    【讨论】:

    • 谢谢!我把我的最后一行换成了你的最后一行,这和上面的答案一样有效:)
    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 2020-11-18
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多