如何打印字典中所选键值的正确值? (Python)
How to print correct value for chosen key value in dictionary? (Python)
我正在制作一本包含不同人生日的字典(用户通过输入填写)。现在,我还希望用户能够输入 he/she 刚刚添加的其中一个姓名,然后在 return 中获取该人的生日。问题是它总是 return 添加到列表中的最后日期,无论用户 wrote.so 说用户将这些元素放在哪个名称中:{anna:1.october, paul :3.january}。如果我希望程序打印 Anna 的生日,它会打印 "anna's birthday is at 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行可能有问题。所有帮助表示赞赏! :)
这是你想要的?但是我觉得还不完整
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)))
首先,在您添加的代码中,我没有看到您将值添加到字典的部分。
之后你可以通过这个搜索:
if find in birthdays:
date = birthdays.get(find)
print(" %s 's birthday is at %s" % (find, date))
我正在制作一本包含不同人生日的字典(用户通过输入填写)。现在,我还希望用户能够输入 he/she 刚刚添加的其中一个姓名,然后在 return 中获取该人的生日。问题是它总是 return 添加到列表中的最后日期,无论用户 wrote.so 说用户将这些元素放在哪个名称中:{anna:1.october, paul :3.january}。如果我希望程序打印 Anna 的生日,它会打印 "anna's birthday is at 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行可能有问题。所有帮助表示赞赏! :)
这是你想要的?但是我觉得还不完整
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)))
首先,在您添加的代码中,我没有看到您将值添加到字典的部分。 之后你可以通过这个搜索:
if find in birthdays:
date = birthdays.get(find)
print(" %s 's birthday is at %s" % (find, date))