实例中的字典迭代不符合预期

时间:2019-01-02 12:10:12

标签: python python-3.x list dictionary iteration

将标量值存储在实例中的列表字典中无法正常工作。

我创建了一个类,该类使用一个字典,该字典的键是数据点的标题,并且其值指向存储数据(标量值)的位置。

在实例化期间,将创建另一个字典,我们将其称为data_collection,它将具有与输入字典相同的键,并且每个键都将得到一个空列表。

在调用实例期间,它应该遍历键和输入字典的值,并将每个输入字典的值附加到data_collection字典中。

当我打印data_collection时出现问题。期望其中的每个列表的长度为1,我感到惊讶,每个列表正是键的长度。

我尝试创建2个独立词典,它可以按预期工作,即每个字典条目都有一个length = 1的列表。请帮助!谢谢!

class DataCollector:
    def __init__(self, data_points):
        self._data_points = data_points
        self._data_collection = dict.fromkeys(self._data_points.keys(), list())


    def __call__(self):
        for name, data_source in self._data_points.items():
            self._data_collection[name].append(data_source)

class DumpGenerator:
    def __init__(self, x):
        self.x = x

dg_1 = DumpGenerator(24)
dg_2 = DumpGenerator(42)
data_collector = DataCollector(data_points={'dg_1': dg_1.x, 'dg_2': dg_2.x})
data_collector()
print(data_collector._data_collection)

预期:

  

{'dg_1':[24],'dg_2':[42]}

但是我得到了:

  

{'dg_1':[24,42],'dg_2':[24,42]}

1 个答案:

答案 0 :(得分:3)

为此替换您的__init__,您的代码将正常工作:

def __init__(self, data_points):
    self._data_points = data_points
    self._data_collection = {k:[] for k in data_points.keys()} # changes are here

之所以发生,是因为您将相同的列表添加到_data_collection的两个不同键中。而当您将它们附加到其中之一时,就像您将一项附加到两者中一样。

有关正在发生的事情的更多信息:Here