Get key by value in dictionary

后端 未结 30 2426
北恋
北恋 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条回答
  •  旧时难觅i
    2020-11-21 07:04

    Consider using Pandas. As stated in William McKinney's "Python for Data Analysis'

    Another way to think about a Series is as a fixed-length, ordered dict, as it is a mapping of index values to data values. It can be used in many contexts where you might use a dict.

    import pandas as pd
    list = {'george':16,'amber':19}
    lookup_list = pd.Series(list)
    

    To query your series do the following:

    lookup_list[lookup_list.values == 19]
    

    Which yields:

    Out[1]: 
    amber    19
    dtype: int64
    

    If you need to do anything else with the output transforming the answer into a list might be useful:

    answer = lookup_list[lookup_list.values == 19].index
    answer = pd.Index.tolist(answer)
    

提交回复
热议问题