Get key by value in dictionary

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

    I tried to read as many solutions as I can to prevent giving duplicate answer. However, if you are working on a dictionary which values are contained in lists and if you want to get keys that have a particular element you could do this:

    d = {'Adams': [18, 29, 30],
         'Allen': [9, 27],
         'Anderson': [24, 26],
         'Bailey': [7, 30],
         'Baker': [31, 7, 10, 19],
         'Barnes': [22, 31, 10, 21],
         'Bell': [2, 24, 17, 26]}
    

    Now lets find names that have 24 in their values.

    for key in d.keys():    
        if 24 in d[key]:
            print(key)
    

    This would work with multiple values as well.

提交回复
热议问题