Get key by value in dictionary

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

    Here is a solution which works both in Python 2 and Python 3:

    dict((v, k) for k, v in list.items())[search_age]
    

    The part until [search_age] constructs the reverse dictionary (where values are keys and vice-versa). You could create a helper method which will cache this reversed dictionary like so:

    def find_name(age, _rev_lookup=dict((v, k) for k, v in ages_by_name.items())):
        return _rev_lookup[age]
    

    or even more generally a factory which would create a by-age name lookup method for one or more of you lists

    def create_name_finder(ages_by_name):
        names_by_age = dict((v, k) for k, v in ages_by_name.items())
        def find_name(age):
          return names_by_age[age]
    

    so you would be able to do:

    find_teen_by_age = create_name_finder({'george':16,'amber':19})
    ...
    find_teen_by_age(search_age)
    

    Note that I renamed list to ages_by_name since the former is a predefined type.

提交回复
热议问题