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

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


当前回答

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


其他回答

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


key = next((k for k in my_dict if my_dict[k] == val), None)

通过“查找”值来查找列表中的键是不容易的。但是,如果知道值,遍历键,就可以按元素在字典中查找值。如果D[element](其中D是一个字典对象)等于你要查找的键,你可以执行一些代码。

D = {'Ali': 20, 'Marina': 12, 'George':16}
age = int(input('enter age:\t'))  
for element in D.keys():
    if D[element] == age:
        print(element)
def get_Value(dic,value):
    for name in dic:
        if dic[name] == value:
            del dic[name]
            return name

这是你访问字典做你想做的事情的方式:

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

当然,你们的名字太离谱了,看起来像是要打印一个年龄,但它确实打印了名字。因为你是通过名字来访问的,所以如果你这样写会更容易理解:

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

更好的是:

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