吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 695|回复: 2
收起左侧

[求助] python查询数据库内容分类成字典

[复制链接]
pjwefan 发表于 2022-12-13 15:06
查询数据库内容:
class,name,age,height,sex

当前可获取的是
data=[
        {"class":"一班","name":"小明","age":"18",height:"180cm","sex":"男"},
        {"class":"一班","name":"小文","age":"17",height:"170cm","sex":"女"},
        {"class":"二班","name":"张三","age":"18",height:"180cm","sex":"男"},
        {"class":"二班","name":"李四","age":"17",height:"170cm","sex":"女"},
]
如何转成下面我需要的数据
date1=
[
        {"class":"一班","info":[{"name":"小明","age":"18",height:"180cm","sex":"男"},{"name":"小文","age":"17",height:"170cm","sex":"女"}]},
        {"class":"二班","info":[{"name":"张三","age":"18",height:"180cm","sex":"男"},{"name":"李四","age":"17",height:"170cm","sex":"女"}]}
]

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

heign 发表于 2022-12-14 20:33
本帖最后由 heign 于 2022-12-14 20:46 编辑

import pandas as pd
df = pd.DataFrame(data)
data1 = []
for i in df['class'].unique():
    dct = {}
    dct['class'] = i
    i_df = df[df['class']==i]
    lst_df = i_df.iloc[:,1:]
    d = lst_df.T.to_dict()
    dct['info'] = []
    for v in d.values():
        dct['info'].append(v)
    data1.append(dct)
print(data1)

通过pandas肯定还有更简单的方法,但我刚入门写得比较啰嗦
mtDNA 发表于 2022-12-19 12:40
个人拙见,就当一次练手,没有使用第三方库

def func(data, column1, column2):
    column1_values=[]
    for row in data:
        value1=row[column1]
        if value1 not in column1_values:
            column1_values.append(value1)   #column1_values==["一班", "二班"]

    data1=[]
    for c1_value in column1_values:
        rows=list(filter(lambda row: row[column1]==c1_value, data))
        c2_value=[]
        for r in rows:
            r1=r.copy()     #直接改rows会导致data变动,因此必须把rows的元素copy到新变量
            r1.pop(column1)
            c2_value.append(r1)
        new_row={column1:c1_value, column2:c2_value}
        data1.append(new_row)

    return data1

>>> data=[
        {"class":"一班","name":"小明","age":"18","height":"180cm","sex":"男"},
        {"class":"一班","name":"小文","age":"17","height":"170cm","sex":"女"},
        {"class":"二班","name":"张三","age":"18","height":"180cm","sex":"男"},
        {"class":"二班","name":"李四","age":"17","height":"170cm","sex":"女"},
        ]
>>> data1=func(data, column1="class", column2="info")
>>> print(data1)
[{'class': '一班', 'info': [{'name': '小明', 'age': '18', 'height': '180cm', 'sex': '男'}, {'name': '小文', 'age': '17', 'height': '170cm', 'sex': '女'}]}, {'class': '二班', 'info': [{'name': '张三', 'age': '18', 'height': '180cm', 'sex': '男'}, {'name': '李四', 'age': '17', 'height': '170cm', 'sex': '女'}]}]
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 04:42

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表