Python 2.7 如何过滤字典

Python 2.7 如何过滤字典,python-2.7,dictionary,filter,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':[(951147466)] 如何过滤这个 这是我的代码中字典的一部分: detected_objects = {} # analyze all worthy detections for x in range(worthy_detections):

输出字典:

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

如何过滤这个

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

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
请帮帮我


提前感谢您

您只需将感兴趣的密钥复制到新的目录中即可:

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初学者,然后我在官方文档中没有看到与我相同的情况,如果你是初学者,谢谢你(作为初学者没有问题,我们都是-现在仍然是-初学者),然后,你想做的第一件事——这也是你在这里发布问题之前所期望做的一部分——是阅读文档并做官方教程(如果有,但现在最常见的情况是,至少对于语言和框架)。如果您已经完成了Python官方教程,您将了解如何从dict获取特定密钥,并从中总结如何基于特定密钥过滤dict。非常感谢您的建议