Python: Convert SELECT query list to dict
Use GROUP_CONCAT
in the query to get all the codes for a city together as a comma-delimited string, then split it up in Python to create a list.
cur.execute("SELECT name, ARRAY_AGG(codcity) FROM cities GROUP BY name")
rows = cur.fetchall()
cities = {}
for row in rows:
cities[row[0]] = [int(code) for code in row[1].split(',')]
This will put the codes in a list, not a dictionary, which is probably better than making up dictionary keys like id-1
, id-2
, etc., e.g.
'New York': [132, 24]
Populate a dictionary with the result of a query
Using list comprehension:
things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]
or using list comprehension with zip
:
things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]
If you use Cursor.description
attribute, you can get column names:
names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]
How to store the sql query result into a dictionary object
d = {}
for x in result:
d.setdefault(x[0], [] ).append(x[2])
for x in d:
while len(d[x]) < 7:
d[x].append(0)
convert sqlalchemy query result to a list of dicts
Try
result_dict = [u.__dict__ for u in my_query.all()]
Besides what is the type of your result_dict
before the for
loop? Its behavior is rather strange.
Related Topics
How to Convert Column With Dtype as Object to String in Pandas Dataframe
In Dictionary, Converting the Value from String to Integer
Is There a Proper Variable to Track How Many Times a Loop Has Looped
Pandas Fill in Missing Date Within Each Group With Information in the Previous Row
Increment Values in a List of Lists Starting from 1
Python Read File Determined by Separator \R\N
How to Downgrade Tensorflow, Multiple Versions Possible
Pandas: Sum Dataframe Rows for Given Columns
Python Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:748)
How to Ignore Null Byte When Reading a CSV File
How to Convert a Float into Hex
Putting Multiple Conditions Using Np.Where on Python Pandas
Python Super :Typeerror: _Init_() Takes 2 Positional Arguments But 3 Were Given
Numpy Distance Calculations of Different Shaped Arrays
Split a Large Json File into Multiple Smaller Files