首页 > 解决方案 > Python API 和字典

问题描述

我试图只打印说两个“设备”,我尝试了多种方法但没有任何运气,我该怎么做?此外,我将如何做一些事情来打印单个设备或什至两者的“模型”。我已经发布了我的代码以及下面的回复。

<class 'dict'>
{'data': {'devices': [{'device': ’00:00:00:00:00:00:00:00’, 'model': 'H6159', 'deviceName': 'Closet', 'controllable': True, 'retrievable': True, 'supportCmds': ['turn', 'brightness', 'color', 'colorTem']}, {'device': '00:00:00:00:00:00:00:00', 'model': 'H6003', 'deviceName': 'Living Room', 'controllable': True, 'retrievable': True, 'supportCmds': ['turn', 'brightness', 'color', 'colorTem']}]}, 'message': 'Success', 'code': 200}

标签: pythonjsonapidictionary

解决方案


如果我理解正确,您希望通过键访问 dict rs 的值。因此,您想使用 rs[key] 访问 dict,例如 rs['data']['devices'][0]['model'] 以获取列表中第一个的设备型号。

rs['data'] -> get the data value of rs which is another dict.
rs['data']['devices'] -> get the devices in data which is a list. So you can access its element by index for example 0.
rs['data']['devices'][0] -> get the first device in the devices list
rs['data']['devices'][0]['model'] -> get the value of first device model. 

推荐阅读