in your terminal from your bench root… and you will get a python console. you can fire your frappe api functions here and test the result. try frapp.sql() or frappe.get_all here and play with python before you can put the code in your py.
Debug what you are getting in query result dict here and do the changes in your code.