在Python中根据字典值寻找键

问题描述

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

label_map = {
    0: 'background', 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'
}

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


解决方案

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

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

# >>> 2

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

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

# >>> 3

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

posted @ 2023-06-15 20:36  絵守辛玥  阅读(104)  评论(0)    收藏  举报