Get key by value in dictionary

后端 未结 30 2820
北恋
北恋 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 06:57

    I found this answer very effective but not very easy to read for me.

    To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.

    mydict = {'george':16,'amber':19}
    res = dict((v,k) for k,v in mydict.iteritems())
    print(res[16]) # Prints george
    

    or

    mydict = {'george':16,'amber':19}
    dict((v,k) for k,v in mydict.iteritems())[16]
    

    which is essentially the same that this other answer.

提交回复
热议问题