pythondictionary-comprehension

How to add an object to a list in a dictionary using class


I have two classes: Fit class and Fit_collection which is collection of instances of Fit class. I also have two lists each element of lists need to be converted to Fit object and need to be saved to Fit_Collection dictionary. The expected output should look like this:

{'project1': [fit1, fit2, fit3], 'project2': [fit11, fit22]}

I don't know how to rewrite my Fit_Collection class in a way that it will add Fit objects to the list. It should be simple, but I can not catch it. Current output is:

{'project1': fit3, 'project2': fit22}

Here is the code:

class Fit_Collection(dict):
    def __init__(self, *args, **kwargs):
        super(Fit_Collection, self).__init__(*args, **kwargs)
    def fit(self, *args, **kwargs):
        f = Fit(*args, **kwargs)
        self[f.project_name] = f
        return f

class Fit(object):
    def __init__(self, name, project_name):
        self.name = name
        self.project_name = project_name

project1 = ["fit1", "fit2", "fit3"]
project2 = ["fit11", "fit22"]

dictionary = Fit_Collection()
for item in project1:
    dictionary.fit(item, "project1")

for item in project2:
    dictionary.fit(item, "project2")

print(dictionary)

Solution

  • Right now, your dictionary values are not lists, but individual class instances. So each time you call fit, it replaces any existing value with the new one, losing the old value.

    To change the dictionary values to lists, you can do:

    class Fit_Collection(dict):
        def __init__(self, *args, **kwargs):
            super(Fit_Collection, self).__init__(*args, **kwargs)
        def fit(self, *args, **kwargs):
            f = Fit(*args, **kwargs)
            if f.project_name in self:
                self[f.project_name].append(f)
            else:
                self[f.project_name] = [f]
            return f
    

    This will append to an existing list if the key already exists, otherwise it will create a list for the new key.