【问题标题】:Dictionary iteration within an instance is not as expected [duplicate]实例中的字典迭代不如预期[重复]
【发布时间】:2019-05-29 02:07:41
【问题描述】:

在实例内的列表字典中存储标量值未按预期工作。

我创建了一个类,它接受一个字典,其中的键是数据点的标题,并且具有指向数据(标量值)存储位置的值。

在实例化过程中,另一个字典被创建,我们称之为data_collection,它与输入字典有相同的键,每个键都会得到一个空列表。

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

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

我尝试创建 2 个独立字典,它按预期工作,即每个字典条目都有一个长度 = 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]}

【问题讨论】:

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


    【解决方案1】:

    用这个替换你的__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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2015-03-31
    • 2020-07-26
    相关资源
    最近更新 更多