Serialization of the user Class in Python
Alternative solution
pets = {"Tom" : Cat("Tom"), "Rex" : Dog("Rex")}print(pets.keys())print(json.dumps(pets))
In the end, there's no way to say "is there a cat or dog in the dictionary" without looping over all the values
You can try this:
import jsonclass Cat(): def __init__(self, name): self.name = nameclass Dog(): def __init__(self, name): self.name = namepets = dict()pets[str(Cat)] = Cat("Tom").__dict__ #he can get the value using pets[str(Cat)] or pets.get(str(Cat),None))pets[str(Dog)] = Dog("Rex").__dict__print(pets.keys())print(json.dumps(pets))