1

I'm trying to convert my SQL Alchemy to a basic dict.

For this case, I'm trying to use the __dict__ builtin function.

But the behavior is quite strange.

Here is my function:

def trial_to_dict(sa_trial_instance):
    """"Convert a SQL Alchemy instance to a JSON dict
    params:
        sa_trial_instance (dict): SQL Alchemy instance
    returns:
        dict: JSON
    """

    temp_dict = sa_trial_instance.__dict__

    return {
        "ct_id": temp_dict["ct_id"],
        "study_type": temp_dict["study_type"],
        "phase": temp_dict["phase"]
    }

sa_trial_instance is defined, and it's a Sql Alchemy instance sa_trial_instance

But temp_dict isn't the result I'm expecting : temp_dict

Obvioulsy, I'm getting this error:

Exception has occurred: KeyError
'ct_id'

Is anyone has an explanation about this? Thank you for your help!

Vivian
  • 321
  • 1
  • 3
  • 10
  • 3
    See https://stackoverflow.com/a/37350445/137650 for a possible utility function to do the conversion for you – MatsLindh Nov 11 '21 at 11:22
  • `'ct_id'` isn't even in your screenshot. – aaron Nov 11 '21 at 12:18
  • 1
    Does this answer your question? [Convert sqlalchemy row object to python dict](https://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict) – funnydman Nov 20 '21 at 14:33

0 Answers0