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?