简体   繁体   中英

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}. If I then want the program to print Anna's birthday, it instead prints "anna's birthday is at 3.january". 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. 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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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