我做了一个函数,它将在字典中查找年龄并显示匹配的名字:

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。我知道这是不正确的,但我不知道如何让它向后搜索。


当前回答

最后我用一个函数来做。这种方法可以避免进行完整的循环,直觉告诉我们,它应该比其他解决方案更快。

def get_key_from_value(my_dict, to_find):

    for k,v in my_dict.items():
        if v==to_find: return k

    return None

其他回答

没有。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)

我认为指出哪些方法是最快的,以及在什么情况下是最快的会很有趣:

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

def method1(dict, search_age):
    for name, age in dict.iteritems():
        if age == search_age:
            return name

def method2(dict, search_age):
    return [name for name,age in dict.iteritems() if age == search_age]

def method3(dict, search_age):
    return dict.keys()[dict.values().index(search_age)]

profile.run()在每个方法上100,000次的结果:

方法1:

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

方法2:

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

方法3:

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

所以这表明,对于一个小字典,方法1是最快的。这很可能是因为它返回第一个匹配,而不是像方法2那样返回所有匹配(参见下面的注释)。


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

方法1:

>>> 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,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds

方法3:

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

这里,方法3要快得多。这表明字典的大小会影响你选择的方法。

注:

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

for name in mydict:
    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
def get_Value(dic,value):
    for name in dic:
        if dic[name] == value:
            del dic[name]
            return name

这是一个奇怪的问题,因为第一条评论就给出了完美的答案。 根据样例提供的数据示例

dictionary = {'george': 16, 'amber': 19}
print(dictionary["george"])

它返回

16

所以你想要相反的结果 输入“16”,得到“george” 简单地交换键值和presto

dictionary = {'george': 16, 'amber': 19}
inv_dict = {value:key for key, value in dictionary.items()}
print(inv_dict[16])

我处于完全相反的位置,因为我有一本字典

{16:'george', 19:'amber'}

我试着喂"乔治"然后得到16个…我尝试了几种循环和迭代器,OK..他们工作,但它不是简单的一行解决方案,我将使用快速结果…所以我简单地交换了解。 如果我错过了什么,请让我知道删除我的答案。