python-3.x - Python字典,通过键名获取值
问题描述
我有嵌套字典,试图迭代它并按键获取值,
我有一个有效载荷,它的路由作为主节点,在路由内部我有很多航路点,我想遍历所有航路点并根据键名将值设置为 protobuff 变量。
下面的示例代码:
'payload':
{
'route':
{
'name': 'Argo',
'navigation_type': 2,
'backtracking': False,
'continuous': False,
'waypoints':
{
'id': 2,
'coordinate':
{
'type': 0,
'x': 51.435989,
'y': 25.32838,
'z': 0
},
'velocity': 0.55555582,
'constrained': True,
'action':
{
'type': 1,
'duration': 0
}
}
'waypoints':
{
'id': 2,
'coordinate':
{
'type': 0,
'x': 51.435989,
'y': 25.32838,
'z': 0
},
'velocity': 0.55555582,
'constrained': True,
'action':
{
'type': 1,
'duration': 0
}
}
},
'waypoint_status_list':
{
'id': 1,
'status': 'executing'
},
'autonomy_status': 3
},
#method to iterate over payload
def get_encoded_payload(self, payload):
#1 fill route proto from payload
a = payload["route"]["name"] #working fine
b = payload["route"]["navigation_type"] #working fine
c = payload["route"]["backtracking"] #working fine
d = payload["route"]["continuous"] #working fine
self.logger.debug(type(payload["route"]["waypoints"])) # type is dict
#iterate over waypoints
for waypoint in payload["route"]["waypoints"]:
wp_id = waypoint["id"] # Error, string indices must be integer
我想遍历所有航点并将每个键值的值设置为一个变量
解决方案
self.logger.debug(type(payload["route"]["waypoints"])) # type is dict
迭代 adict
会给你它的键。您以后的代码似乎期望多个航路点作为 a list
of dict
s,这会起作用,但这不是您的结构实际包含的内容。
试试看print(waypoint)
你会得到什么。
推荐阅读
- c - 在 RSL10 评估和开发套件中使用 BLE
- nixos - 如何从 configuration.nix 更改 nixpkgs 中定义的服务的 serviceConfig?
- python - 无法解析 JSON 文件和设计查询中的值
- dynamics-365 - 在更新 Dynamics CRM 365 Online 实体之前是否必须检索
- wordpress - Woocommerce 电子邮件变量未转换
- java - 在 Java 中反转嵌套的 TreeMap
- php - Laravel orderBy datetime 和时区
- bash - /bin/sh:在 Docker 容器中找不到 my_custom 命令
- c++ - 在容器排列中使用 C++ 适配器和库函数对象
- javascript - url-loader configuration in webpack is loading the images from different path in React JS project