Python - 将Dict分组的元组

时间:2017-02-14 17:19:50

标签: python json tuples

所以我从我的数据库中返回了这个元组,它显示了用户每天登录的次数。

mytuple = 
(
    ('jim', datetime.date(2017, 2, 10), 1L), 
    ('jeff', datetime.date(2017, 2, 11), 1L), 
    ('jeff', datetime.date(2017, 2, 12), 1L), 
    ('jeff', datetime.date(2017, 2, 13), 1L), 
    ('jeff', datetime.date(2017, 2, 14), 26L)
)

如何以这种方式将其格式化为Dict / Json?

mydict = {
    {
        name: 'jeff',
        data: [
            [(2017, 2, 11), 1],
            [(2017, 2, 12), 1],
            [(2017, 2, 13), 1],
            [(2017, 2, 14), 26]
        ]
    },
    {
        name: 'jim',
        data: [
            [(2017, 2, 10), 1]
        ]
    }
    }

3 个答案:

答案 0 :(得分:1)

您还可以使用itertools库,它具有groupby功能。希望一旦你有更大的数据集,这将更快。但是,输出将是列表而不是字典,与您提出的不完全相同。

import datetime
from itertools import groupby

mytuple = [('jim', datetime.date(2017, 2, 10), 1), 
    ('jeff', datetime.date(2017, 2, 11), 1), 
    ('jeff', datetime.date(2017, 2, 12), 1), 
    ('jeff', datetime.date(2017, 2, 13), 1), 
    ('jeff', datetime.date(2017, 2, 14), 26)]

group_dict = []
for key, group in groupby(mytuple, lambda x: x[0]):
    group_dict.append({'name': key, 'data': [[g[1], g[2]] for g in group]})

在这里你做groupby并使用元组的第一个键为它提供功能,例如这里lambda x: x[0]。这种情况下的数据是每个组索引1和2的元素。

您也可以使用元组格式的转换日期时间,如下所示:

group_dict = []
for key, group in groupby(mytuple, lambda x: x[0]):
    data = [[(g[1].year, g[1].month, g[1].day), g[2]] for g in group]
    group_dict.append({'name': key, 'data': data})

答案 1 :(得分:0)

import datetime
import json

mytype = (
    ('jim', datetime.date(2017, 2, 10), 1L), 
    ('jeff', datetime.date(2017, 2, 11), 1L), 
    ('jeff', datetime.date(2017, 2, 12), 1L), 
    ('jeff', datetime.date(2017, 2, 13), 1L), 
    ('jeff', datetime.date(2017, 2, 14), 26L)
)

mydict = {}

for name, date, count in mytype:
    if name not in mydict:
        mydict[name] = []
    mydict[name].append(((date.year, date.month, date.day), count))

print mydict
print json.dumps(mydict)

答案 2 :(得分:0)

您可以使用以下内容:

import datetime
import json

mytype = (
    ('jim', datetime.date(2017, 2, 10), 1L),
    ('jeff', datetime.date(2017, 2, 11), 1L),
    ('jeff', datetime.date(2017, 2, 12), 1L),
    ('jeff', datetime.date(2017, 2, 13), 1L),
    ('jeff', datetime.date(2017, 2, 14), 26L)
)

output = []

def date_to_ymd_tuple(input_date):
    return (input_date.year, input_date.month, input_date.day)

for user in set(item[0] for item in mytype):
    output.append({'name': user,
                   'data': [[date_to_ymd_tuple(x[1]), x[2]] for x in mytype if x[0] == user]
                   })

print output

with open('output.txt', 'w') as f:
    json.dump(output, f)

将写出

[{"data": [[[2017, 2, 10], 1]], "name": "jim"}, {"data": [[[2017, 2, 11], 1], [[2017, 2, 12], 1], [[2017, 2, 13], 1], [[2017, 2, 14], 26]], "name": "jeff"}]