在Python中根据字典值寻找键

发布时间 2023-06-15 20:42:01作者: 绘守辛玥

问题描述

  在处理VOC数据集时,创建的字典如下所示

label_map = {
    1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat', 5: 'bottle', 6: 'bus', 7: 'car', 
    8: 'cat', 9: 'chair', 10: 'cow', 11: 'diningtable', 12: 'dog', 13: 'horse', 14: 'motorbike', 
    15: 'person', 16: 'pottedplant', 17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor', 0: 'background'
}

  根据标注文件格式,寻找标注文件中的label并将其所对应的key添加到label_map列表中。


解决方案

  这个问题可以转化为List来解决。首先我们先回忆下在List中根据值寻找下标的方法,如下

a = [2, 3, 7, 9, 1, 8]
a.index(7)

# >>> 2

  根据这个办法,我们将字典转化为列表,并求其所对应值的下标+1即为键(列表起始为0)

label = 'bird'
idx = list(label_map.values()).index(label) + 1
print(idx)

# >>> 3

*注: 该字典排序需要为顺序