根据字典的键更新Python字典中的列表

2024-06-26 01:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个字典,它根据可用设备的数量自动初始化,如下所示:

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)

你可能注意到我为每个设备初始化了一个空列表值。之后我想为每个列表添加不同的项,因此我创建了使用self.dictLists的函数,并尝试为相应的设备添加项,如下所示:

        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

它的工作,但不是预期的!因为一旦出现属于不同设备的新项目,就会删除以前的设备项目,并且只满足新设备列表。也许print self.dictLists的输出有助于理解问题。你知道吗

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

当新设备出现时会发生这种情况:

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

我试过使用self.dictLists.setdefault(k, []).append(item),但效果也一样。 任何帮助或解释都将不胜感激。你知道吗


Tags: theinself列表ifdeviceitemcon
1条回答
网友
1楼 · 发布于 2024-06-26 01:41:50

在您的功能中:

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

相反,只需将device的值添加到self.dictLists作为key,默认值为[]。为此,使用dict.setdefault()作为:

self.dictLists.setdefault(device, [])

相关问题 更多 >