Have a nested dictionary.
stock_price = {'lastPrice': 129.1,
'open': 126.57,
'close': 0,
'intraDayHighLow': {'min': 126.4, 'max': 129.55, 'value': 129.1},
'weekHighLow': {'min': 49.7, 'minDate': '26-Jun-2023',
'max': 142.9,
'maxDate': '30-Apr-2024',
'value': 129.1},
}
…which is converted it to a dataclass, as follows.
from dataclasses import dataclass
def create_dataclass_from_dict(data_dict: dict, class_name:str):
fields = {}
for key, value in data_dict.items():
if isinstance(value, dict):
nested_class_name = key.capitalize()
nested_class = create_dataclass_from_dict(value, class_name=nested_class_name)
fields[key] = nested_class
else:
fields[key] = value
return dataclass(type(class_name, (), fields))
….but when I see the dict of the instance, it shows an empty set…
Stock = create_dataclass_from_dict(stock_price, 'Stock')
my_stock = Stock()
my_stock.__dict__ # gives {}
…and so not able to convert it back to a dictionary using the following code:
import json
def to_dict(obj):
return json.loads(json.dumps(obj, default=lambda o: o.__dict__))
to_dict(my_stock) # gives {}
Where am I going wrong? Why is the .__dict__
empty?