首页 > 解决方案 > 如何访问嵌套字典python中的元素

问题描述

我是 python 新手,非常感谢您的帮助。我有一个包含键值对的 JSON 文件。基本上我必须提取“区域”内的“all_points_x”和“所有点在解决问题。json_data 文件内容

_via_img_metadata {'barley_Admixture_image28.jpg2218': {'filename': 'barley_Admixture_image28.jpg', 'size': 2218, 'regions': [{'shape_attributes': {'name': 'polygon', 'all_points_x': [35, 28, 27, 31, 40, 51, 62, 72, 74, 71, 65, 57, 41], 'all_points_y': [74, 55, 32, 16, 4, 6, 12, 35, 56, 74, 83, 86, 81]}, 'region_attributes': {}},

for i in range(len(json_data[keys]['regions'])):
            coords = []
            for j in range(len(json_data[keys]['regions'][i]['shape_attributes']['all_points_x'])):
                coords.append((json_data[keys]['regions'][i]['shape_attributes']['all_points_x'][j], json_data[keys]['regions'][i]['shape_attributes']['all_points_y'][j]))
            coords = np.asarray([coords], dtype=np.int32)
            if i == 0:
                mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
                cv2.polylines(mask, coords, isClosed=True, color=255, thickness=4)
            else:
                mask1 = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
                cv2.polylines(mask1, coords, isClosed=True, color=255, thickness=4)
                mask = cv2.bitwise_or(mask,mask1)

标签: python

解决方案


您可以像这样访问嵌套字典中的项目

for key,value in dictionary.items():
    for k,v in value.items()
        #do sth

据我了解,您的 json_data 下面的代码应该可以工作。

coords = []

for key,value in json_data.items():
    regions = value['regions']
    for i in range(len(regions)):
        for x,y in zip(regions[i]['shape_attributes']['all_points_x'],regions[i]['shape_attributes']['all_points_y']):
            coords.append((x,y)) 

推荐阅读