Get key by value in dictionary

后端 未结 30 3059
北恋
北恋 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:05

    You can get key by using dict.keys(), dict.values() and list.index() methods, see code samples below:

    names_dict = {'george':16,'amber':19}
    search_age = int(raw_input("Provide age"))
    key = names_dict.keys()[names_dict.values().index(search_age)]
    

提交回复
热议问题