我有一个 python 脚本,其中有一个 SQL 查询返回到列表列表中,例如:
result = [ ['12345', 'Red', 'House', 150, '18/05/2016', 27.3],
['34534', 'Blue', 'Car', 500, '22/12/2015', 587.52] ]
每个列表中的第一项是 ID,然后每一项是与每条记录相关的属性,例如 Colour
、Type
、Size
、日期
、成本
。
对于每个 SQL 查询运行,诸如 Colour
、Date
等项目属性可能会有所不同,因为这些属性是从另一个查询结果动态添加到我的 SQL 查询中的(其中查询列)例如:
columns = {'RecID': 'RecordID', 'Color': 'Colour', 'Type': 'Type', 'Size': 'Size', 'PurchaseDate': 'Date', 'PurchaseCost': 'Cost'}
newQueryFields = "[UniqueID]"
for x in columns:
newQueryFields = "{}, [{}]".format(newQueryFields, columns[x])
我已经设法使用以下代码将其放入列表字典中,但对于代码的其余部分(尚未编写),如果我可以引用字典项会更好。
newResult = dict()
for rec in result:
newResult[rec[0]] = rec
结果是:
result = {'12345': ['12345', 'Red', 'House', 150, '18/05/2016', 27.3],
'34534': ['34534', 'Blue', 'Car', 500, '22/12/2015', 587.52] }
但是我试图将结果放入字典的字典中(我认为?),但我无法理解如何构建要输出的代码:
newResult = {'12345': {'ID': '12345', 'Colour': 'Red', 'Type': 'House', 'Size': 150, 'Date': '18/05/2016', 'Cost': 27.3},
'34534': {'ID': '34534', 'Colour': 'Blue', 'Type': 'Car', 'Size': 500, 'Date': '22/12/2015', 'Cost': 587.52} }
最佳答案
这是为了让您了解如果您已经有了列
,您可以做什么:
columns = ['ID', 'Colour', 'Type', 'Size', 'Date', 'Cost']
newResult = {rec[0]: dict(zip(columns, rec)) for rec in result}
显然,您需要首先获取在您的案例中动态添加的列
。
关于Python 转换查询输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37290882/