通過字典中的值獲取鍵

本文翻譯自:Get key by value in dictionary

I made a function which will look up ages in a Dictionary and show the matching name: 我做了一個函數,可以在Dictionary查詢年齡並顯示匹配的名稱:

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

I know how to compare and find the age I just don't know how to show the name of the person. 我知道如何比較和查找年齡,但我不知道如何顯示此人的名字。 Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards. 另外,由於第5行,我得到了KeyError 。我知道這是不正確的,但我不知道如何使它向後搜索。


#1樓

參考:https://stackoom.com/question/XfEA/通過字典中的值獲取鍵


#2樓

lKey = [key for key, value in lDictionary.iteritems() if value == lValue][0]

#3樓

for name in mydict.keys():
    if mydict[name] == search_age:
        print name 
        #or do something else with it. 
        #if in a function append to a temporary list, 
        #then after the loop return the list

#4樓

mydict = {'george':16,'amber':19}
print mydict.keys()[mydict.values().index(16)] # Prints george

Or in Python 3.x: 或在Python 3.x中:

mydict = {'george':16,'amber':19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position. 基本上,它將字典中的值分隔在一個列表中,找到您擁有的值的位置,並在該位置獲取鍵。

More about keys() and .values() in Python 3: Python: simplest way to get list of values from dict? 有關Python 3中的keys().values()更多信息: Python:從dict獲取值列表的最簡單方法?


#5樓

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) 這是我運行的一些測試(在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: 每個方法上profile.run()結果100000次:

Method 1: 方法1:

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

Method 2: 方法2:

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

Method 3: 方法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. 因此,這表明對於小的字典而言,方法1最快。 This is most likely because it returns the first match, as opposed to all of the matches like method 2 (see note below). 這很可能是因爲它返回第一個匹配項,而不是像方法2那樣的所有匹配項(請參見下面的註釋)。


Interestingly, performing the same tests on a dict I have with 2700 entries, I get quite different results (this time run 10000 times): 有趣的是,對我擁有2700個條目的字典執行相同的測試,我得到的結果完全不同(這次運行10000次):

Method 1: 方法1:

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

Method 2: 方法2:

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

Method 3: 方法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. 所以在這裏,方法3是快得多 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. 注意:方法2返回所有名稱的列表,而方法1和3僅返回第一個匹配項。 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. 我不確定方法3是否創建2個額外的列表(keys()和values())並將它們存儲在內存中。


#6樓

it's answered, but it could be done with a fancy 'map/reduce' use, eg: 它得到了回答,但是可以通過花哨的“ map / reduce”用法來完成,例如:

def find_key(value, dictionary):
    return reduce(lambda x, y: x if x is not None else y,
                  map(lambda x: x[0] if x[1] == value else None, 
                      dictionary.iteritems()))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章