Python的Dict根据value找到key

104 阅读1分钟

def get_dict_key_desc(dic, value): keylist = list(dic.keys()) valuelist = list(dic.values()) index = valuelist.index(value) key = keylist[index] return key

经典写法,根据字典的值value获得该值对应的key

def get_dict_key(dic, value): key = list(dic.keys())[list(dic.values()).index(value)] return key

**思路:** python的dict相当于java的Map,键值对组成,是一对一关系,那么找到值的位置,就相当于找到了键的位置,取出即可。