Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization of the user Class in Python

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?

like image 815
Aganezor Avatar asked Apr 08 '26 23:04

Aganezor


2 Answers

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

like image 125
OneCricketeer Avatar answered Apr 11 '26 11:04

OneCricketeer


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))
like image 23
Taohidul Islam Avatar answered Apr 11 '26 11:04

Taohidul Islam