Get key by value in dictionary

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

    my_dict = {'A': 19, 'B': 28, 'carson': 28}
    search_age = 28
    

    take only one

    name = next((name for name, age in my_dict.items() if age == search_age), None)
    print(name)  # 'B'
    

    get multiple data

    name_list = [name for name, age in filter(lambda item: item[1] == search_age, my_dict.items())]
    print(name_list)  # ['B', 'carson']
    

提交回复
热议问题