如何在for循环中存储字典

how to store a dictionary within a for loop

我想将数据值存储在我的字典{}中,但出现错误。

mydict= {}
for entity in entities:
     if entity.entity_id.startswith('sensor'):
         list = remote.get_state(api, entity.entity_id)
         data = {list.attributes['friendly_name'] : list.state}
         for key, val in data.items():
             mydict+= {key:val}

我收到以下错误。

mydict+= {key:val}
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'

与直觉上的想法相反,如错误所示,类型 dictdict 不支持 += 运算符。字典与列表略有不同,+= 不像某种连接运算符那样工作。

但是,为什么不使用 += 运算符,您为什么不像下面的代码片段那样尝试更新内部 for 循环范围?

mydict= {}
for entity in entities:
    if entity.entity_id.startswith('sensor'):
        list = remote.get_state(api, entity.entity_id)
        data = {list.attributes['friendly_name'] : list.state}
        for key, val in data.items():
            mydict[key] = val

或者,您可以进行批量更新,如下所示。

mydict= {}
for entity in entities:
    if entity.entity_id.startswith('sensor'):
        list = remote.get_state(api, entity.entity_id)
        data = {list.attributes['friendly_name'] : list.state}
        mydict.update(data)