首页 > 解决方案 > 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
    

我想遍历所有航点并将每个键值的值设置为一个变量

标签: python-3.xdictionary

解决方案


self.logger.debug(type(payload["route"]["waypoints"])) # type is dict

迭代 adict会给你它的键。您以后的代码似乎期望多个航路点作为 a listof dicts,这会起作用,但这不是您的结构实际包含的内容。

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


推荐阅读