Python 在字典中按值获取键

Python 在字典中按值获取键,python,dictionary,Python,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 我知道如何比较和找出年龄,但我不知道如何显示这个人的名字。此

我制作了一个函数,可以在
字典中查找年龄,并显示匹配的名称:

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
我知道如何比较和找出年龄,但我不知道如何显示这个人的名字。此外,由于第5行的原因,我得到了一个
KeyError
。我知道这不正确,但我不知道如何让它向后搜索。

如果您想要姓名和年龄,您应该使用
.items()
,它将为您提供键
(键,值)
元组:

for name, age in mydict.items():
    if age == search_age:
        print name
您可以在
for
循环中将元组解压为两个单独的变量,然后匹配年龄

你也应该考虑翻阅字典,如果你一般都是按年龄看,没有两个人有相同的年龄:

{16: 'george', 19: 'amber'}
所以你可以通过简单的操作来查找一个年龄的名字

mydict[search_age]
我一直称它为
mydict
而不是
list
,因为
list
是内置类型的名称,您不应该将该名称用于其他任何内容

您甚至可以在一行中获得具有给定年龄的所有人的列表:

[name for name, age in mydict.items() if age == search_age]
或者,如果每个年龄只有一个人:

next((name for name, age in mydict.items() if age == search_age), None)
这只会给你
,如果没有同龄的人

<> P>最后,如果<代码> DIST很长,你在Python 2上,你应该考虑使用<代码> .ItIdTimes()/Cl>而不是<代码>。
它为您提供键
(键,值)
元组:

for name, age in mydict.items():
    if age == search_age:
        print name
您可以在
for
循环中将元组解压为两个单独的变量,然后匹配年龄

你也应该考虑翻阅字典,如果你一般都是按年龄看,没有两个人有相同的年龄:

{16: 'george', 19: 'amber'}
所以你可以通过简单的操作来查找一个年龄的名字

mydict[search_age]
我一直称它为
mydict
而不是
list
,因为
list
是内置类型的名称,您不应该将该名称用于其他任何内容

您甚至可以在一行中获得具有给定年龄的所有人的列表:

[name for name, age in mydict.items() if age == search_age]
或者,如果每个年龄只有一个人:

next((name for name, age in mydict.items() if age == search_age), None)
这只会给你
,如果没有同龄的人


<>最后,如果<代码> DICT很长,你在Python 2上,你应该考虑使用<代码> .ItItIdMe()/Cl>而不是<代码>。code>dict不打算以这种方式使用

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)

没有
dict
不打算以这种方式使用

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)
或者在Python 3.x中:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george
基本上,它在一个列表中分隔字典的值,找到您拥有的值的位置,并在该位置获取键

有关Python 3中的
keys()
.values()
的详细信息:

或者在Python 3.x中:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george
基本上,它在一个列表中分隔字典的值,找到您拥有的值的位置,并在该位置获取键


关于Python 3中的
keys()
.values()
的更多信息:

我想指出哪些方法是最快的,以及在什么情况下:

以下是我(在2012年MacBook Pro上)进行的一些测试

def方法1(记录、搜索):
在dict.iteritems()中,姓名、年龄为:
如果年龄==搜索年龄:
返回名称
定义方法2(dict、搜索年龄):
返回[name for name,dict.iteritems()中的年龄,如果年龄==搜索年龄]
定义方法3(dict、搜索年龄):
返回目录键()[目录值().索引(搜索年龄)]
每个方法的
profile.run()
结果100000次:

方法1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds
>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds
方法2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds
>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds
方法3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds
>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds
这表明对于一个小的dict,方法1是最快的。这很可能是因为它返回第一个匹配项,而不是像方法2这样的所有匹配项(请参见下面的注释)


有趣的是,在我有2700个条目的dict上执行相同的测试,我得到了完全不同的结果(这次运行10000次):

方法1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds
>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds
方法2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds
>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds
方法3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds
>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds
所以在这里,方法3要快得多。只需显示dict的大小将影响您选择的方法

注:

  • 方法2返回所有名称的列表,而方法1和3只返回第一个匹配项
  • 我没有考虑内存使用。我不确定方法3是否创建了两个额外的列表(
    keys()
    values()
    )并将它们存储在内存中

我想指出哪种方法最快以及在什么情况下最快会很有趣:

以下是我(在2012年MacBook Pro上)进行的一些测试

def方法1(记录、搜索):
在dict.iteritems()中,姓名、年龄为:
如果年龄==搜索年龄:
返回名称
定义方法2(dict、搜索年龄):
返回[name for name,dict.iteritems()中的年龄,如果年龄==搜索年龄]
定义方法3(dict、搜索年龄):
返回目录键()[目录值().索引(搜索年龄)]
每个方法的
profile.run()
结果100000次:

方法1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds
>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds
方法2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds
>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds
方法3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds
>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds
这表明对于一个小的dict,方法1是最快的。这很可能是因为它返回第一个匹配项,而不是像方法2这样的所有匹配项(请参见下面的注释)


有趣的是,在我有2700个条目的dict上执行相同的测试,我得到了完全不同的结果(这次运行10000次):

方法1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds
>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds
方法2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds
>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds
方法3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds
>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds
所以在这里,方法3要快得多。只需显示dict的大小将影响您选择的方法

注:

  • 方法2返回所有名称的列表,而方法1和3只返回第一个匹配项
  • 我没有考虑内存使用。我不确定方法3是否会创建2个额外的l
    names_dict = {'george':16,'amber':19}
    search_age = int(raw_input("Provide age"))
    key = names_dict.keys()[names_dict.values().index(search_age)]
    
    import pandas as pd
    list = {'george':16,'amber':19}
    lookup_list = pd.Series(list)
    
    lookup_list[lookup_list.values == 19]
    
    Out[1]: 
    amber    19
    dtype: int64
    
    answer = lookup_list[lookup_list.values == 19].index
    answer = pd.Index.tolist(answer)
    
    get_key = lambda v, d: next(k for k in d if d[k] is v)
    
    def getKey(dct,value):
         return [key for key in dct if (dct[key] == value)]
    
    mydict = {'george':16,'amber':19}
    res = dict((v,k) for k,v in mydict.iteritems())
    print(res[16]) # Prints george
    
    mydict = {'george':16,'amber':19}
    res = dict((v,k) for k,v in mydict.items())
    print(res[16]) # Prints george
    
    print(res.get(16)) # Prints george
    
    reversed_dictionary = dict(map(reversed, dictionary.items()))
    
    d = {'Adams': [18, 29, 30],
         'Allen': [9, 27],
         'Anderson': [24, 26],
         'Bailey': [7, 30],
         'Baker': [31, 7, 10, 19],
         'Barnes': [22, 31, 10, 21],
         'Bell': [2, 24, 17, 26]}
    
    for key in d.keys():    
        if 24 in d[key]:
            print(key)
    
    filter( lambda x, dictionary=dictionary, search_age=int(search_age): dictionary[x] == search_age  , dictionary )
    
    >>> dictionary = {'george' : 16, 'amber' : 19, 'frank': 19}
    >>>
    >>> age = 19
    >>> name = [k for k in dictionary.keys() if dictionary[k] == age]; name
    ['george', 'frank']
    >>>
    >>> age = (16, 19)
    >>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
    ['george', 'amber', 'frank']
    >>>
    >>> age = (22, 25)
    >>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
    []