0

I have a dictionary of type dict[str,list[MyClass]] in my class. I need to define a method addElement. I would like it to add a new key-value pair (with an empty list) if the key doesn't exist, and otherwise put the specified c value into the existing list.

Now, when I print the result I have all the keys needed so this part works fine. The problem is that every list has only 1 element inside. I checked the result with some print and I found out that my code never enters in the if statement it just jumps to else. I think I did all checks needed so something is missing...

This is the code :

class MyDict:
    items:dict[str,list[MyClass]]={}

    # other stuff omitted

    def addElement(self, p: str, c: MyClass):
        tmp: list[MyClass] = self.items.get(p)
        if(tmp == None or len(tmp) == 0):
            print("key not exists, inserting")
            self.items.update({p : [c]})
        else:
            print("existing key, adding")
            self.items.update({p : [c]+tmp})

How can I fix this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Finley Adams
  • 773
  • 1
  • 8
  • 20
  • As an aside, you do understand that `items` as described here belongs to *the class itself*, and **not** to individual instances, yes? Anyway, if the linked duplicates don't help, then the problem is somewhere else - for example, the `p` values that you expect to match don't actually match, or something like that. You would need to ask again, making sure that you have a [MVCE](https://stackoverflow.com/help/minimal-reproducible-example). – Karl Knechtel Oct 03 '21 at 18:29
  • @KarlKnechtel yes I DO understand that it belongs to the class itself. There is also a constructor but I didn't wrote it. If you asked me before closing the question I could add some code. Maybe I'm missing your suggestion, can you be more explicit? – Finley Adams Oct 03 '21 at 18:34
  • @KarlKnechtel Ok thanks I will create a better question then. By the way I think the problem is that I created the dictionary using {} while I should use "defaultDic" I will check – Finley Adams Oct 03 '21 at 18:36
  • See the linked duplicates. You asked how to make a dictionary with values that are lists, such that a new list is created when necessary, and appended to otherwise. The linked duplicates suggest various approaches for this problem. The code you have written is too much work for the problem, but I can't directly see how it would cause a failure - not without 1) enough code that someone else can copy and paste; 2) an exact sequence of input that causes the problem; 3) an exact description of what happens, what is supposed to happen instead, and how that is different. – Karl Knechtel Oct 03 '21 at 18:36
  • @KarlKnechtel mh ok I will be more careful next time thanks – Finley Adams Oct 03 '21 at 18:43

0 Answers0