Convert sqlalchemy query result to dicts list

I want the result of my query to be converted to a dicts list as follows:

result_dict = [{'category': 'failure', 'week': '1209', 'stat': 'tdc_ok', 'severityDue': '2_critic'}, {'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severityDue': '2_critic'}] 

But instead, I get it as a dict, this way with duplicate keys:

 result_dict = {'category': 'failure', 'week': '1209', 'stat': 'tdc_ok', 'severityDue': '2_critic', 'category': 'failure', 'week': '1210', 'stat': 'tdc_nok', 'severityDue': '2_critic'} 

I get this result by doing this:

 for u in my_query.all(): result_dict = u.__dict__ 

How to convert sqlAlchemy query result to dicts list (each row will be dict)?

help me please

+7
source share
3 answers

Try

 result_dict = [u.__dict__ for u in my_query.all()] 

Also, what is the type of your result_dict before the for loop? This behavior is rather strange.

+10
source

No. all ()

You can try:

 result_dict = [u.__dict__ for u in my_query.fetchall()] 
+2
source

Now it works

 result_dict = [u._asdict() for u in my_query.all()] 

The reason is that u is not really a tuple, but KeyedTuple.

A correct answer to this thread would also be helpful.

+1
source

Source: https://habr.com/ru/post/949720/


All Articles