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

迭代dict得到它的键。你后来的代码似乎期望多个路径点作为dicts的list,这将工作,但这不是你的结构实际包含的。

试试print(waypoint),看看你会得到什么。

最新更新