【问题标题】:Converting nested python lists to database将嵌套的 python 列表转换为数据库
【发布时间】:2013-02-08 22:00:48
【问题描述】:

我有一个 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 数据库的格式获取它?基本上,我想重新排列它,使其类似于易于传输的表格/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 的了解也很薄弱,所以我希望有其他快速的方法来转换这些数据...

如果我使用嵌套字典结构而不是嵌套列表会有帮助吗?

【问题讨论】:

  • 这是一个列表有什么原因吗?看起来它对我来说应该是一个字典。
  • 我对 python 的了解还不够,但是是的,我绝对应该为这个应用程序使用字典。谢谢!

标签: python database list dictionary nested


【解决方案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

【讨论】:

  • 谢谢!这绝对是我一直在寻找的——在这种情况下使用 translate 函数的价值是什么?
【解决方案2】:

我可能误解了这个问题,但是要将您的列表输出为 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% 将数据放到正确的位置。

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    相关资源
    最近更新 更多