TJR TJR - 22 days ago 5
Python Question

Updating list in Python dictionaries depending on dictionary's key

I created a dictionary that is initialized automatically according to the number of devices available as follow:

def _sensors_discovery(self,con, req):

if self.sensors[0] in con.labels:
device = con.resourceName
if device not in self.device_list: # get all the devices
self.device_list.append(device)
self.dictLists = dict((key, []) for key in self.device_list)


A you may noticed I initialized for each device or "key" an empty list as value.After this i want to append for each list different items therefore i created this functions that uses
self.dictLists
and tried to append items for the corresponding device as follow:

for k, v in self.dictLists.iteritems():
if k in item: # the item contain already the device name therefore i check here if the device name is in the item and then i append it to the list of the corresponding device
v.append(items)
print self.dictLists


it works but not as expected! because what happen is that as soon as a new items that belong to different device appears, the previous device items are deleted and only the new device list is fulfilled. Maybe the output of
print self.dictLists
helps to understand the problem.

{u'device1': [u'item1']}
{device1': [u'item1', u'item2']}
{device1': [u'item1', u'item2', u'item3']}


then this happen when a new device appears:

{u'device2': [u'item1_d2], u'device1': []}
{u'device2': [u'item1_d2, u'item2_d2'], u'device1': []}
...


i tried with
self.dictLists.setdefault(k, []).append(item)
but it works the same way as well.
Any help or explanation would be appreciated.

Answer

In your function:

def _sensors_discovery(self,con, req):
    if self.sensors[0] in con.labels:
        device = con.resourceName
        if device not in self.device_list:  # get all the devices
            self.device_list.append(device)
            self.dictLists = dict((key, []) for key in self.device_list)  
            # ^ ^ ^ Here you are re-initializing the dict

Instead, you need to just add the value of device to self.dictLists as key with default value as []. For that use dict.setdefault() as:

self.dictLists.setdefault(device, [])