row.Row and dict behavior in 2.0

3,972 views
Skip to first unread message

mkmo...@gmail.com

unread,
Jan 9, 2023, 8:50:27 PM1/9/23
to sqlalchemy
Hello,

It looks like in 2.0 we can no longer treat a row.Row as a dict. I have a few cases where I want to do this, such as when I need to get a list of columns, or when I don't know the column name in advance.

    rows = conn.execute(select(t.c.foo)).fetchall()

    rows[0].keys()  # Not Allowed

    rows[0][some_unknown_column]  # not allowed

If we need to treat it as a dict, are we supposed to be calling:

    rows[0]._asdict()

This works, but the only issue is that our IDEs flag this as accessing a protected member of a class. Is there any alternative?

Thanks and best regards,

Matthew

Mike Bayer

unread,
Jan 9, 2023, 9:00:08 PM1/9/23
to noreply-spamdigest via sqlalchemy
you have more options here than previously on how to treat rows, as tuples or mappings, either up front or on a per-row basis.  the new API has been  available as of version 1.4.  Relevant links include:

1. announcement of change and rationale


2. migration guide


3. new tutorial coverage


included is background on how to get mappings from a Row or how to get RowMapping objects from a result up front using result.mappings().







Matthew


--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

mkmo...@gmail.com

unread,
Jan 12, 2023, 1:46:56 PM1/12/23
to sqlalchemy
Hi Mike,

Thanks. I have a few cases where it is easiest if I have a plain dict instead of a RowMapping. For example RowMapping is immutable, and isn't playing nicely with my json encoder.

What is your preferred method to convert to a plain dict?

    Row._asdict()
    dict(RowMapping.items())
    something else?

Thanks and best regards,

Matthew


Mike Bayer

unread,
Jan 12, 2023, 2:00:58 PM1/12/23
to noreply-spamdigest via sqlalchemy


On Thu, Jan 12, 2023, at 1:46 PM, mkmo...@gmail.com wrote:
Hi Mike,

Thanks. I have a few cases where it is easiest if I have a plain dict instead of a RowMapping. For example RowMapping is immutable, and isn't playing nicely with my json encoder.

What is your preferred method to convert to a plain dict?

for row in result.mappings():
    d = dict(row)

should do it

the row was not mutable in 1.4, 1.3, etc. either, what did you do then ?

mkmo...@gmail.com

unread,
Jan 13, 2023, 12:10:12 PM1/13/23
to sqlalchemy
Hi Mike,

That's much more concise, thank you.

Previously I have always accessed the  `_asdict()` private member.

Thanks and best regards,

Matthew

Reply all
Reply to author
Forward
0 new messages