有一個使用場景,需要在Python的字典中,根據值獲取字典中對應的key值。
step1 首先需要判斷value值是否存在於字典中
dict.values()
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
>>> True
step1 若值在字典中,返回對應的key值
list(dict.keys())[list(dict.values()).index('one')]
>>> list(d.keys())[list(d.values()).index('one')] #根據字典值 返回對應的key
>>> '1'