8

What would be the best way of storing a python list of numbers (such as [4, 7, 10, 39, 91]) to a database? I am using the Pyramid framework with SQLAlchemy to communicate to a database.

Thanks!

Rafał Dowgird
  • 43,216
  • 11
  • 77
  • 90
retnuh
  • 590
  • 3
  • 6
  • 16

4 Answers4

22

You can use json to save your arrays in db as stings:

In [1]: import json

In [2]: json.dumps([1, 2, 3])
Out[2]: '[1, 2, 3]'

In [3]: json.loads(json.dumps([1, 2, 3]))
Out[3]: [1, 2, 3]

also consider using cjson for better performances and anyjson for nice fallbacks.

neurino
  • 11,500
  • 2
  • 40
  • 63
  • `cjson` looks interesting. I didn't realize JSON performance was something to be concerned with, but I see a bunch of benchmarking info of different JSON python libs. [Here's](https://github.com/rtyler/py-yajl/blob/master/compare.py) a nice comparison script I found from [another SO question](http://stackoverflow.com/questions/706101/python-json-decoding-performance). – Banjer Aug 11 '13 at 15:30
  • is the performance of cjson still better than the one of json? – Sadık Aug 19 '15 at 13:24
8

Well conceptually you can store a list as a bunch of rows in a table using a one-to-many relation, or you can focus on how to store a list in a particular database backend. For example postgres can store an array in a particular cell using the sqlalchemy.dialects.postgres.ARRAY data type which can serialize a python array into a postgres array column.

Michael Merickel
  • 23,153
  • 3
  • 54
  • 70
0

sqlalchemy.types.PickleType can store list

Pegasus
  • 1,398
  • 15
  • 20
0

Use string(Varchar). From Zen of Python: "Simple is better than complex."

Eugene Nagorny
  • 1,626
  • 3
  • 18
  • 32