仅将唯一值存储在json输出的字典列表中

时间:2013-07-31 00:21:44

标签: python list dictionary python-3.x

数据源是带有2个连接的Mysql查询。 Query返回一个值列表,如下所示:

title   start   additive

title1  5885    NULL
title2  8829    add1
title2  8829    add2
title3  3697    NULL

正如您所看到的,当有多于1个添加剂时,JOIN查询会创建title / start的重复项。标题应该是唯一的,添加剂应该添加到列表中。

我的最终目标是以下列格式输出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

0 个答案:

没有答案