【发布时间】:2017-11-09 13:10:45
【问题描述】:
我是 python 新手,在尝试将嵌套字典中的数据插入 MySQLdb 时遇到了问题。我有一本看起来像这样的字典,但要长得多,并且长度可以变化。
d = {
'Object_a': {
'parameter_1': {
'Cost': 12.00,
'Markup': 23.4555
},
'parameter_2': {
'Cost': 45.22,
'Markup': 11.222,
'Height': 44.33
}
},
'Object_b': {
'parameter_3': {
'Length': 12.00,
'Width': 23.4555
},
'parameter_1': {
'Cost': 1.12,
'Area': 4,
'Volume': 16.72
}
}
}
我一直在到处寻找一种方法来将嵌套字典操作到下面的表单中。 (我不知道怎么做表格,所以它是 csv 样式的,抱歉)
Object, Parameter, Cost, Markup, Height, Length, Width, Area, Volume
Object_a, parameter_1, 12.00, 23.4555, , , , , ,
Object_a, parameter_2, 45.22, 11.222, 44.33, , , , ,
Object_b, parameter_3, , , , 12.00, 23.4555, ,
Object_b, parameter_2, 1.12, , , , , 4, 16.72
我将数据输入 SQL 数据库的代码如下所示:
目前它需要在程序的另一部分中提供给它的数据库名称、表名称和字典。目前这会检查是否创建了一个表,如果没有创建一个,如果创建了一个,它将检查哪些列存在,如果有新列,它将添加它们并将值插入新列和现有列。
我并不担心这些代码,但我主要担心的是不知道如何将一个字典传递给该函数以获取所需的形式,或者如何遍历上述嵌套字典。
def tablecreate(cursor, tablename, dict):
# Creates a list of keys to use as column names
cols = list(dict.keys())
# If warning occurs, no table exists so create one
try:
sqlcheck = "SELECT 1 FROM {} LIMIT 1".format(tablename)
cursor.execute(sqlcheck)
except:
sql = "CREATE TABLE IF NOT EXISTS %s (ID INT AUTO_INCREMENT, PRIMARY
KEY(ID))" %(tablename)
cursor.execute(sql)
# Creating the rest of the columns
for i in range(0, len(cols)):
sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
cols[i])
cursor.execute(sql)
#Creates a list of new columns to be inserted into Table
sql = "SELECT COLUMN_NAME FROM information_schema.columns WHERE
TABLE_NAME ='%s'" % (tablename)
cursor.execute(sql)
a = cursor.fetchall()
b=[element for tupl in a for element in tupl]
new_cols = [x for x in cols if x not in b]
print (new_cols)
for i in range(0, len(new_cols)):
sql = "ALTER TABLE %s ADD COLUMN %s VARCHAR (50)" % (tablename,
new_cols[i])
cursor.execute(sql)
# Inserting values into the created columns
placeholders = ', '.join(['%s'] *len(dict))
columns = ', '.join(dict.keys())
sql = "INSERT INTO %s (%s) VALUES (%s)" % (tablename, columns,
placeholders)
cursor.execute(sql, dict.values())
【问题讨论】:
标签: python mysql python-3.x dictionary mysql-python