Get key by value in dictionary

后端 未结 30 2847
北恋
北恋 2020-11-21 06:28

I made a function which will look up ages in a Dictionary and show the matching name:

dictionary = {\'george\' : 16, \'amber\' : 19}
search_age          


        
30条回答
  •  耶瑟儿~
    2020-11-21 07:04

    here is my take on it. This is good for displaying multiple results just in case you need one. So I added the list as well

    myList = {'george':16,'amber':19, 'rachel':19, 
               'david':15 }                         #Setting the dictionary
    result=[]                                       #Making ready of the result list
    search_age = int(input('Enter age '))
    
    for keywords in myList.keys():
        if myList[keywords] ==search_age:
        result.append(keywords)                    #This part, we are making list of results
    
    for res in result:                             #We are now printing the results
        print(res)
    

    And that's it...

提交回复
热议问题