在 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