【问题标题】:Store unigue values only in a list of dictionaries for json output仅将唯一值存储在 json 输出的字典列表中
【发布时间】: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


【解决方案1】:

由于 titlestart 的组合是独一无二的,因此您可以利用这一事实,将这两者的元组作为 defaultdict 的键:

from collections import defaultdict

data = [
    ['title1', '5885', '-', 'NULL', ...],
    ['title2', '8829', '-', 'add1', ...],
    ['title2', '8829', '-', 'add2', ...],
    ['title3', '3697', '-', 'NULL', ...],
]

stages = defaultdict(list)
for stage in data:
    title, start, additive = stage[0], stage[1], stage[3]
    stages[(title, start)].append(additive)

>>> from pprint import pprint
>>> pprint(stages)
{('title1', '5885'): ['NULL'],
 ('title2', '8829'): ['add1', 'add2'],
 ('title3', '3697'): ['NULL']}
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多