pjwefan 发表于 2022-12-13 15:06

python查询数据库内容分类成字典

查询数据库内容:
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==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
      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==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': '女'}]}]
```
页: [1]
查看完整版本: python查询数据库内容分类成字典