Search code examples
pythondictionaryfor-loopstore

how to store a dictionary within a for loop


I want to store the values of data in a dictionary my dict{} but i got an error.

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}

I got the following Error.

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

Solution

  • Contrary to one may intuitively think, as the error indicates, += operator is not supported for types dict & dict. Dictionaries are a little different than lists, and += does not work like some sort of concatenation operator for them.

    However, instead of using += operator, why don't you try updating the inner for loop scope as done in the following snippet?

    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
    

    Alternatively, you can do a bulk update, as given below.

    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)