Get key by value in dictionary

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

    If you want both the name and the age, you should be using .items() which gives you key (key, value) tuples:

    for name, age in mydict.items():
        if age == search_age:
            print name
    

    You can unpack the tuple into two separate variables right in the for loop, then match the age.

    You should also consider reversing the dictionary if you're generally going to be looking up by age, and no two people have the same age:

    {16: 'george', 19: 'amber'}
    

    so you can look up the name for an age by just doing

    mydict[search_age]
    

    I've been calling it mydict instead of list because list is the name of a built-in type, and you shouldn't use that name for anything else.

    You can even get a list of all people with a given age in one line:

    [name for name, age in mydict.items() if age == search_age]
    

    or if there is only one person with each age:

    next((name for name, age in mydict.items() if age == search_age), None)
    

    which will just give you None if there isn't anyone with that age.

    Finally, if the dict is long and you're on Python 2, you should consider using .iteritems() instead of .items() as Cat Plus Plus did in his answer, since it doesn't need to make a copy of the list.

提交回复
热议问题