我有字典数据 = {21: False, 22: False, 23: False, 31: False}
如果我检查这种类型,它会以
我正在尝试迭代它并将值分配给 protobuff 变量,下面是我的示例代码
def get_encoded_payload(self, payload):
self.logger.debug("started")
// my payload data looks like this
// payload= {21: False, 22: False, 23: False, 31: False}
#set proto attributes of device status using json data
device_status = DeviceStatusMsg()
device = Device()
#loop over current device status and set the each device state inot device proto
for each_device in payload:
device.type = each_device["device_type"] // Getting error here [ 'int' object is not subscriptable ]
device.state = each_device["device_status"]
我正在尝试将 key, value
分配给 device.type and device.state
答案 0 :(得分:0)
def get_encoded_payload(payload):
for key,value in payload.items():
# dictonery cannot be iterated the way you are iterating hence you are getting
# Getting error here [ 'int' object is not subscriptable ]
b = key
a = value
print("a",a)
print("b",b)
payload= {21: False, 22: False, 23: False, 31:False}
print(type(payload))
get_encoded_payload(payload)
您以错误的方式增加了 python 字典。我建议你阅读https://realpython.com/iterate-through-dictionary-python/。请查看上面的代码片段以供您参考。