【发布时间】:2013-07-31 00:21:43
【问题描述】:
数据来源是Mysql查询,有2个join。查询返回一个值列表,如下所示:
title start additive
title1 5885 NULL
title2 8829 add1
title2 8829 add2
title3 3697 NULL
如您所见,当添加超过 1 个时,JOIN 查询会创建标题/开始的重复项。标题应该是唯一的,并且应该将添加剂添加到列表中。
我的最终目标是按以下格式输出 json 数据:
[
{
title: 'some-title',
start: '584487',
additives: [ 'add1': 58, 'add2': 98 ]
},
{
etc...
},
{
etc...
}
]
我现在正在做的是创建一个列表并用字典对象填充它。但是我得到重复。如何将值添加到列表中,以便获得唯一的标题和任意数量的添加剂列表?
根据我对 python 的有限理解,似乎没有直接的方法来实现这一点。
在 PHP 中,使用关联数组会很简单:
foreach ...
stages[stageTitle]['start'] = '8585';
stages[stageTitle]['additives'] = [];
//and to add to additives on title duplicate
stages[stageTitle]['additives'].push(new Array('additiveTitle' => '58'))
我的代码:
# sql query here...
data = self.cursor.fetchall()
stages = []
for stage in data:
title= stage[0]
start = stage[1]
additive = stage[3]
# I am stuck from here on.
# I cant use keys for list as they have to be numeric
# and I can't append to dict object
# tulpe is immutable so no good here either
【问题讨论】:
-
对于我想要的东西来说似乎有点矫枉过正,但也许它只是超出了我的想象。您能否发布一个我将如何使用它的示例?
标签: python list dictionary python-3.x