UserDict列表

时间:2017-07-18 02:35:43

标签: python data-structures

我相信我做了一个我无法找到的小错误概念。基本上,我正在设计一个简单的数据容器来保存{key1:[values1],key2:[values2]}。

class Cells(object):
    def __init__(self, **kwargs):
        self.data = {}

    def __data_len__(self):
        """ Length of data[first key] list. """
        _ = 0
        for key in self.data.keys():
            if self.data[key]:
                _ = len(self.data[key])
                break
        return _

    def subtract_lists(self, x, y):
        return [item for item in x if item not in y]

    def add(self, to_add):
        """ Add columns if not exist """
        if not set(to_add.keys()).issubset(self.data.keys()):       # New key means adding
            new_keys = self.subtract_lists(to_add.keys(), \
                                            self.data.keys())       # it to our dict
            newdict = dict.fromkeys(new_keys, \
                                    [] * self.__data_len__())
            self.data.update(newdict)

        [self.data[key].append(to_add.get(key, '')) for key in self.data.keys()]
        print('* Updated data is: %s' % self.data)

##############################
# Now, tests...              #
##############################
if __name__ == '__main__':
    cells = Cells()
    cells.add({'one':1, 'two':2, 'three': 3})

期望的输出如下:

Updated data is: {'one': [1], 'two': [2], 'three': [3]}

但输出:

Updated data is: {'one': [1, 2, 3], 'two': [1, 2, 3], 'three': [1, 2, 3]}

即。将每个值添加到每个键,这是令人沮丧的。在某处错字?

1 个答案:

答案 0 :(得分:2)

问题是你要将newdict中的所有值分配为相同的空列表。请参阅此处以获取相关行为的解释:Python initializing a list of lists。该值仅被评估一次,并且字典中的所有值都存储相同的列表对象。

顺便说一下,[] * n(对于任何n)仍然只是[]

更改此行:

    newdict = dict.fromkeys(new_keys, \
                                [] * self.__data_len__()) 

到此:

    newdict = {key: [] for key in new_keys}