Get key by value in dictionary

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

    I thought it would be interesting to point out which methods are the quickest, and in what scenario:

    Here's some tests I ran (on a 2012 MacBook Pro)

    >>> def method1(list,search_age):
    ...     for name,age in list.iteritems():
    ...             if age == search_age:
    ...                     return name
    ... 
    >>> def method2(list,search_age):
    ...     return [name for name,age in list.iteritems() if age == search_age]
    ... 
    >>> def method3(list,search_age):
    ...     return list.keys()[list.values().index(search_age)]
    

    Results from profile.run() on each method 100000 times:

    Method 1:

    >>> profile.run("for i in range(0,100000): method1(list,16)")
         200004 function calls in 1.173 seconds
    

    Method 2:

    >>> profile.run("for i in range(0,100000): method2(list,16)")
         200004 function calls in 1.222 seconds
    

    Method 3:

    >>> profile.run("for i in range(0,100000): method3(list,16)")
         400004 function calls in 2.125 seconds
    

    So this shows that for a small dict, method 1 is the quickest. This is most likely because it returns the first match, as opposed to all of the matches like method 2 (see note below).


    Interestingly, performing the same tests on a dict I have with 2700 entries, I get quite different results (this time run 10000 times):

    Method 1:

    >>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
         20004 function calls in 2.928 seconds
    

    Method 2:

    >>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
         20004 function calls in 3.872 seconds
    

    Method 3:

    >>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
         40004 function calls in 1.176 seconds
    

    So here, method 3 is much faster. Just goes to show the size of your dict will affect which method you choose.

    Notes: Method 2 returns a list of all names, whereas methods 1 and 3 return only the first match. I have not considered memory usage. I'm not sure if method 3 creates 2 extra lists (keys() and values()) and stores them in memory.

提交回复
热议问题