简体   繁体   English

如何在字典中为所选键值打印正确的值? (蟒蛇)

[英]How to print correct value for chosen key value in dictionary? (Python)

I'm making a dictionary with different people's birthdays (Which the user fills in via input). 我正在用不同的人的生日制作一本字典(用户通过输入来填写)。 Now, I also want the user to be able to write in one of the names that he/she just added, and then get that person's birthday in return. 现在,我还希望用户能够使用他/她刚刚添加的名称之一进行书写,然后得到该人的生日。 The problem is that it always returns the last date added to the list, regardless of which name the user wrote.so say the user have put these elements in: {anna:1.october, paul: 3.january}. 问题在于,无论用户写了哪个名字,它总是返回添加到列表中的最后一个日期。所以说用户已将这些元素放在:{anna:1.october,paul:3.january}中。 If I then want the program to print Anna's birthday, it instead prints "anna's birthday is at 3.january". 如果然后我希望该程序打印安娜的生日,则打印“安娜的生日是1月3日”。 This is what my code looks like (Btw, it's roughly translated to English, so don't mind potential language mistakes): 这是我的代码的样子(顺便说一句,它大致翻译成英文,所以不要介意潜在的语言错误):

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))

I feel like there might be something wrong within the last 4 lines. 我觉得最后4行中可能有问题。 All help appreciated! 所有帮助表示赞赏! :) :)

First, in the code that you have added I don't see the part that you add the values to the dictionary. 首先,在您添加的代码中,我看不到将值添加到字典的部分。 After that you can search by this: 之后,您可以通过以下方式进行搜索:

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

This is you want? 这是你想要的吗? But i think it is not complete 但我认为这还不完整

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM