通过字典中的值获取键

本文翻译自: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()))

你可能感兴趣的:(通过字典中的值获取键)