python - 如何访问嵌套字典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)
解决方案
您可以像这样访问嵌套字典中的项目
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))
推荐阅读
- python - 为什么使用 python 而不是 Flask-CLI 运行烧瓶应用程序会产生 ImportError?
- python - 是否有 R 或 Python 函数用于分隔非分隔字符串中的信息,其中信息会有所不同?
- typescript - 无法将严格为 false 的自由形式对象实体模型分配
- python - How to connect to Spark master in Swarm mode from host
- sql-server - 使用 SaveFileDialog vb.net 备份 SQL Server 数据库
- r - 使用向量更改多个列名
- python - 导入tensorflow时出现很多警告
- android - 导航组件 - 共享元素转换根本不起作用
- java - 当我想运行项目时如何修复'log 4 j logger'?
- android - Android 许可协议是否与 Android SDK 许可协议相同?