Greg Morris
Greg Morris

Reputation: 189

Order of column names with keys() in SQLAlchemy

Can I rely on keys() to always return column names in the same order as the query results when selecting all columns? Based on my output it appears to be true, but I can't find any documentation that guarantees it. I'm inclined to think it is true because while dictionaries may be unordered, they should be consistent.

    # Loop through each table in the database where all tables 
    # are being reflected at once.
    for table in Base.metadata.tables.values():

        # Select all columns
        rows = Session.query(table).all()

        # Prepend a header row
        rows.insert(0, rows[0].keys())

        # Output to file
        fh = open(filename, 'wb')
        outcsv = unicodecsv.writer(fh)
        outcsv.writerows(rows)
        fh.close

Similarly, column_descriptions also appears to return names in the same order as the values, but again I am not certain if it will always be true.

    # Prepend list of column names as the first row
    rows.insert(0, [col['name'] for col in Session.query(table).column_descriptions])

Any help will be much appreciated. Thanks!

Upvotes: 2

Views: 771

Answers (1)

The rows returned are KeyedTuples; the ordering of them in 1 query is dictated by the order of the columns in the original select, which will absolutely guarantee that the order is the same as returned by .keys(), and the same for each item of in the same query results.

Upvotes: 1

Related Questions