如何过滤字典

时间:2019-03-18 01:20:18

标签: python-2.7 dictionary filter

输出字典:

{u'person': [(95, 11, 474, 466)],
 u'chair': [(135, 410, 276, 587)], 
 u'book': [(127, 380, 161, 396)]}

我只需要u'person': [(95, 11, 474, 466)]

如何过滤?

这是我的代码中词典的一部分:

detected_objects = {}
# analyze all worthy detections
for x in range(worthy_detections):

    # capture the class of the detected object
    class_name = self._categories[int(classes[0][x])]

    # get the detection box around the object
    box_objects = boxes[0][x]

    # positions of the box are between 0 and 1, relative to the size of the image
    # we multiply them by the size of the image to get the box location in pixels
    ymin = int(box_objects[0] * height)
    xmin = int(box_objects[1] * width)
    ymax = int(box_objects[2] * height)
    xmax = int(box_objects[3] * width)

    if class_name not in detected_objects:
        detected_objects[class_name] = []


    detected_objects[class_name].append((ymin, xmin, ymax, xmax))
detected_objects = detected_objects
print detected_objects

请帮助我

提前谢谢

1 个答案:

答案 0 :(得分:0)

您可以简单地将感兴趣的键复制到新字典中:

detected_objects  = {u'person': [(95, 11, 474, 466)], 
                     u'chair': [(135, 410, 276, 587)], 
                     u'book': [(127, 380, 161, 396)]}

keys_to_keep = {u'person'}

# dictionary comprehension
filtered_results = { k:v for k,v in detected_objects.items() if k in keys_to_keep}
print  filtered_results 

输出:

{u'person': [(95, 11, 474, 466)]}

请参见Python Dictionary Comprehension