将嵌套的python列表转换为数据库

时间:2013-02-08 22:00:48

标签: python database list dictionary nested

我有一个python列表,其结构如下:

apts = [ [2083, \
           [ ["price", "$1000 / month"], \
             ["sq ft.", "500"], \
             ["amenities", "gym hardwood floor"]]], \
          [1096, \ 
           [ ["price", "$1200 / month"], \
             ["sq ft.", "700"], \
             ["a/c", "true"]]], \
          [76, \ 
           [ ["price", "$1100 / month"], \
             ["Pets", "true"], \
             ["a/c", "true"]]]] 

如何以一种格式将其转换为mysql数据库?基本上,我想重新安排它,使其类似于一个易于转移的table / csv文件,如:

id, price, sq ft, amenities, a/c, pets
2083, $1000 / month, 500, gym hardwood floor, ,
1096, $1200 / month, 700, , true,
76, $1100 / month, , true, true

提前致谢。我可以想办法逐一映射这些,但看起来效率很低,而且我对python的了解很少,所以我希望还有其他快速方法来转换这些数据......

如果我使用嵌套字典结构代替嵌套列表会不会有用呢?

2 个答案:

答案 0 :(得分:1)

我可能误解了这个问题,但要将您的列表输出为csv,您会:

import csv

out_file = open('/path/to/out_file.csv', 'wb')
writer = csv.writer(out_file, quoting=csv.QUOTE_ALL)
for data_row in apts:
    writer.writerow(data_row)

要导入到SQL中(假设您的列表已正确排序并且您已正确转义数据)

import MySQLdb
mysql = MySQLdb.connect(host=host, user=user,passwd=passwd,db=db)
cursor = self.mysql.cursor()
queries = []
for row in apts:
    queries.append("('%s')" % "','".join(row) ) #< this will join the data encapsuled in apostrophes
cursor.execute( "INSERT INTO TABLE VALUES %s" % ",".join(queries) ) #< Insert the data

如果您要将数据转储到数据库中,我肯定会建议您使用字典,以便100%将数据转移到正确的位置。

答案 1 :(得分:1)

我的理解是,你的困难在于将复杂的结构转换为价值观。以下是如何做到的:

from collections import OrderedDict

out = []

for r in apts:
    row = OrderedDict([('id',''), ('price',''), ('sqft',''), 
                       ('amenities',''),('ac',''),('pets','')])        
    row['id']=r[0]
    for sr in r[1]:
        row[sr[0].lower().translate(None," ./")]=sr[1]
    out.append(row)

#print result        
for o in out:
    s = ",".join(map(str, o.values()))
    print s

打印

2083,$1000 / month,500,gym hardwood floor,,
1096,$1200 / month,700,,true,
76,$1100 / month,,,true,true