如何从Python数组中提取指定元素并赋值给其他变量
解决方法
你给出的response是嵌套的字典+列表结构,response['sensors'][0]取到的是列表第一个位置的字典对象,只需要再补一层字典的键取值即可:
response = {u'sensors': [{u'objid_raw': 28295, u'objid': 28295}], u'treesize': 1, u'prtg-version': u'21.3.71.1416'} # 提取objid对应的值(和objid_raw的值都是28295,按需取即可) objid = response['sensors'][0]['objid'] # 如果要取objid_raw的值就替换成: # objid = response['sensors'][0]['objid_raw']
如果需要兼容异常场景(比如sensors为空、或者不存在对应键),可以加判断避免报错:
objid = None # 先判断sensors存在且不为空 if response.get('sensors') and len(response['sensors']) > 0: # 安全取值,不存在对应键时返回None objid = response['sensors'][0].get('objid')
内容的提问来源于stack exchange,提问作者cs-tech
相关产品推荐
相关产品推荐

