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

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


当前回答

正如有人提到的,可能有多个键具有相同的值,如下面的my_dict。此外,可能没有匹配的键。

my_dict ={'k1':1,'k2':2, 'k3':1, 'k4':12, 'k5':1, 'k6':1, 'k7':12}

这里有三种找到钥匙的方法,一种用于最后一次敲击,两种用于第一次敲击。

def find_last(search_value:int, d:dict):
    
    return [x for x,y in d.items() if y==search_value].pop()

def find_first1(search_value:int, d:dict):
    return next(filter(lambda x: d[x]==search_value, d.keys()), None)

def find_first2(search_value:int, d:dict):
    return next(x for x,y in  d.items() if y==search_value)

在这些函数中,find_first1比其他函数快一点,如果没有匹配的键,它将返回None。

其他回答

以下是我对这个问题的看法。:) 我刚刚开始学习Python,所以我称之为:

“初学者可以理解的”解决方案。

#Code without comments.

list1 = {'george':16,'amber':19, 'Garry':19}
search_age = raw_input("Provide age: ")
print
search_age = int(search_age)

listByAge = {}

for name, age in list1.items():
    if age == search_age:
        age = str(age)
        results = name + " " +age
        print results

        age2 = int(age)
        listByAge[name] = listByAge.get(name,0)+age2

print
print listByAge

.

#Code with comments.
#I've added another name with the same age to the list.
list1 = {'george':16,'amber':19, 'Garry':19}
#Original code.
search_age = raw_input("Provide age: ")
print
#Because raw_input gives a string, we need to convert it to int,
#so we can search the dictionary list with it.
search_age = int(search_age)

#Here we define another empty dictionary, to store the results in a more 
#permanent way.
listByAge = {}

#We use double variable iteration, so we get both the name and age 
#on each run of the loop.
for name, age in list1.items():
    #Here we check if the User Defined age = the age parameter 
    #for this run of the loop.
    if age == search_age:
        #Here we convert Age back to string, because we will concatenate it 
        #with the person's name. 
        age = str(age)
        #Here we concatenate.
        results = name + " " +age
        #If you want just the names and ages displayed you can delete
        #the code after "print results". If you want them stored, don't...
        print results

        #Here we create a second variable that uses the value of
        #the age for the current person in the list.
        #For example if "Anna" is "10", age2 = 10,
        #integer value which we can use in addition.
        age2 = int(age)
        #Here we use the method that checks or creates values in dictionaries.
        #We create a new entry for each name that matches the User Defined Age
        #with default value of 0, and then we add the value from age2.
        listByAge[name] = listByAge.get(name,0)+age2

#Here we print the new dictionary with the users with User Defined Age.
print
print listByAge

.

#Results
Running: *\test.py (Thu Jun 06 05:10:02 2013)

Provide age: 19

amber 19
Garry 19

{'amber': 19, 'Garry': 19}

Execution Successful!

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

def get_key_from_value(my_dict, to_find):

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

    return None

已经回答了,但由于一些人提到反转字典,下面是如何在一行中做到这一点(假设1:1映射)和一些各种性能数据:

python 2.6:

reversedict = dict([(value, key) for key, value in mydict.iteritems()])

+ 2.7:

reversedict = {value:key for key, value in mydict.iteritems()}

如果你认为不是1:1,你仍然可以用几行创建一个合理的反向映射:

reversedict = defaultdict(list)
[reversedict[value].append(key) for key, value in mydict.iteritems()]

这有多慢:比简单的搜索慢,但远没有你想象的那么慢——在一个“直接”100000条目的字典上,“快速”搜索(即查找键前面的值)比反转整个字典快10倍左右,而“缓慢”搜索(接近结尾)大约快4-5倍。所以最多查找10次,就能收回成本。

第二个版本(每个项目都有列表)大约是简单版本的2.5倍。

largedict = dict((x,x) for x in range(100000))

# Should be slow, has to search 90000 entries before it finds it
In [26]: %timeit largedict.keys()[largedict.values().index(90000)]
100 loops, best of 3: 4.81 ms per loop

# Should be fast, has to only search 9 entries to find it. 
In [27]: %timeit largedict.keys()[largedict.values().index(9)]
100 loops, best of 3: 2.94 ms per loop

# How about using iterkeys() instead of keys()?
# These are faster, because you don't have to create the entire keys array.
# You DO have to create the entire values array - more on that later.

In [31]: %timeit islice(largedict.iterkeys(), largedict.values().index(90000))
100 loops, best of 3: 3.38 ms per loop

In [32]: %timeit islice(largedict.iterkeys(), largedict.values().index(9))
1000 loops, best of 3: 1.48 ms per loop

In [24]: %timeit reversedict = dict([(value, key) for key, value in largedict.iteritems()])
10 loops, best of 3: 22.9 ms per loop

In [23]: %%timeit
....: reversedict = defaultdict(list)
....: [reversedict[value].append(key) for key, value in largedict.iteritems()]
....:
10 loops, best of 3: 53.6 ms per loop

过滤器也有一些有趣的结果。理论上,filter应该更快,因为我们可以使用itervalues(),而且可能不需要创建/遍历整个值列表。在实践中,结果是……奇怪的……

In [72]: %%timeit
....: myf = ifilter(lambda x: x[1] == 90000, largedict.iteritems())
....: myf.next()[0]
....:
100 loops, best of 3: 15.1 ms per loop

In [73]: %%timeit
....: myf = ifilter(lambda x: x[1] == 9, largedict.iteritems())
....: myf.next()[0]
....:
100000 loops, best of 3: 2.36 us per loop

因此,对于小偏移量,它比以前的任何版本都要快得多(2.36 *u*S vs.以前的情况下至少1.48 *m*S)。然而,对于接近列表末尾的大偏移量,它会显着变慢(15.1ms vs.相同的1.48mS)。以我之见,在低端产品上节省下来的少量成本,在高端产品上的成本是不值的。

dict_a = {'length': 5, 'width': 9, 'height': 4}

# get the key of specific value 5
key_of_value = list(dict_a)[list(dict_a.values()).index(5)]
print(key_of_value)  # length

# get the key of minimum value
key_min_value = list(dict_a)[list(dict_a.values()).index(sorted(dict_a.values())[0])]
print(key_min_value)  # height

# get the key of maximum value
key_max_value = list(dict_a)[list(dict_a.values()).index(sorted(dict_a.values(), reverse=True)[0])]
print(key_max_value)  # width


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

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..他们工作,但它不是简单的一行解决方案,我将使用快速结果…所以我简单地交换了解。 如果我错过了什么,请让我知道删除我的答案。