2

Storing scalar values in a dictionary of lists within an instance is not working as expected.

I've created a class that takes a dictionary with keys that are the title of data points and has values that point to the location where data (scalar values) are stored.

During instantiation, another dictionary is created, let's call it data_collection, and will have the same key as the input dictionary, and each key will get an empty list.

During calls to the instance, it should iterate through the keys, and the values of the input dictionary, and append the values from each input dictionary to the data_collection dictionary.

The problem happens when I print data_collection. Expecting each list in it being the length of 1, I get a surprise, each list is exactly the length of the keys.

I tried creating 2 free-standing dictionaries, and it works as expected, i.e. each dictionary entry got a list of length = 1. Please help! thanks!

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)

expected:

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

but I got:

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

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
Boon
  • 56
  • 7

1 Answers1

3

Replace your __init__ with this, your code will work fine:

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

that happened because you add the same list to both different keys of _data_collection. and when you append to one of them it will like you append an item to both.

For more information that what is happening : Here

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59