在 dict 中搜索键的值

dict 没有用于搜索值或键的内置方法,因为字典是无序的。你可以创建一个获取指定值的键(或键)的函数:

def getKeysForValue(dictionary, value):
    foundkeys = []
    for keys in dictionary:
        if dictionary[key] == value:
            foundkeys.append(key)
    return foundkeys

这也可以写成等效的列表理解:

def getKeysForValueComp(dictionary, value): 
    return [key for key in dictionary if dictionary[key] == value]

如果你只关心一个找到的密钥:

def getOneKeyForValue(dictionary, value):
    return next(key for key in dictionary if dictionary[key] == value)

前两个函数将返回具有指定值的所有 keyslist

adict = {'a': 10, 'b': 20, 'c': 10}
getKeysForValue(adict, 10)     # ['c', 'a'] - order is random could as well be ['a', 'c']
getKeysForValueComp(adict, 10) # ['c', 'a'] - dito
getKeysForValueComp(adict, 20) # ['b']
getKeysForValueComp(adict, 25) # []

另一个只返回一个键:

getOneKeyForValue(adict, 10)   # 'c'  - depending on the circumstances this could also be 'a'
getOneKeyForValue(adict, 20)   # 'b'

如果值不在 dict 中,则提高 StopIteration-Exception

getOneKeyForValue(adict, 25)

StopIteration