Black
Black

Reputation: 4644

Python: SQL query results to table

I have the results for a SQL query in Python and I would like to convert this into a table with the appropriate data formats.

The results now:

(datetime.datetime(2014, 1, 13, 0, 0), Decimal('6.16'), Decimal('5.95'), Decimal('4.05')),

I would like the results to be:

13/01/14, 6.16, 5.95, 4.05

I have tried:

Data = list(conn.execute(# some query));
Stuff = [];
for row in Data:
Stuff.append([i for i in zip(time.strftime("%d %m %Y", row['day'].timetuple()), float(row['col1']), float(row['col2']), float(row['col3']))]);

But this seems to only zip by 1 character and not each element separated by ','. Is there a way to zip by delimiter? Or any alternative implementation to get the desired result.

EDIT

The solution previously suggested creates a list with [day, a1, a2, a3] i.e. n x 1 table vs n x 4 table i.e. day, a1, a2, a3 which is required. Is there any way to do this using zip or something similar?

Upvotes: 0

Views: 134

Answers (2)

Black
Black

Reputation: 4644

Stuff = []
for row in Data:
    Stuff.append([i for i in [row['day'], float(row['a1']), float(row['a2']), float(row['a3'])]]);

Upvotes: 0

Peter Gibson
Peter Gibson

Reputation: 19554

You don't need zip. zip takes multiple lists and interleaves them

>>> zip('abc', '123')
[('a', '1'), ('b', '2'), ('c', '3')]

Just append the data straight to your Stuff list

Data = list(conn.execute(# some query));
Stuff = [];
for row in Data:
    Stuff.append([time.strftime("%d %m %Y", row['day'].timetuple()), float(row['col1']), float(row['col2']), float(row['col3'])])

Upvotes: 1

Related Questions