Get key by value in dictionary

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

    mydict = {'george': 16, 'amber': 19}
    print mydict.keys()[mydict.values().index(16)]  # Prints george
    

    Or in Python 3.x:

    mydict = {'george': 16, 'amber': 19}
    print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george
    

    Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

    More about keys() and .values() in Python 3: How can I get list of values from dict?

提交回复
热议问题