I want to use the type of the object as a dictionary key with the possibility to serialize such dictionary into JSON string, preferably. With the possibility to de-serialize it and then use simple "if SomeType in SomeDictionary" check.
The minimum code example that demonstrates the issue:
import json
class Cat():
def __init__(self, name):
self.name = name
class Dog():
def __init__(self, name):
self.name = name
pets = dict()
pets[Cat] = Cat("Tom")
pets[Dog] = Dog("Rex")
print(pets.keys())
print(json.dumps(pets))
I get the error:
dict_keys([<class '__main__.Cat'>, <class '__main__.Dog'>])
Traceback (most recent call last):
File "python", line 17, in <module>
TypeError: keys must be a string
The line 17 indicates the line with "print(json.dumps(pets))".
Is it possible to implement such behavior 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 json
class Cat():
def __init__(self, name):
self.name = name
class Dog():
def __init__(self, name):
self.name = name
pets = 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With