使用python中的词典列表

2024-10-04 01:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典的清单,请看下面

raw_list = [
    {"item_name": "orange", "id": 12, "total": 2},
    {"item_name": "apple", "id": 12},
    {"item_name": "apple", "id": 34, "total": 22},
]

预期产出应为

[
    {"item_name": ["orange", "apple"], "id": 12, "total": 2},
    {"item_name": "apple", "id": 34, "total": 22},
]

但我是怎么得到的

[
    {"item_name": "orangeapple", "id": 12, "total": 2},
    {"item_name": "apple", "id": 34, "total": 22},
]

这是我的密码

comp_key = "id"
conc_key = "item_name"
res = []
for ele in test_list:
    temp = False
    for ele1 in res:
        if ele1[comp_key] == ele[comp_key]:
            ele1[conc_key] = ele1[conc_key] + ele[conc_key]
            temp = True
            break
    if not temp:
        res.append(ele)

如何解决


Tags: keynameidappleforresitemtemp
3条回答

您可以使用itertools.grouper按id进行分组,并使用collections.defaultdict将具有相同键的值组合到列表中

from itertools import groupby
from collections import defaultdict

id_getter = lambda x: x['id']
gp = groupby(sorted(raw_list, key=id_getter), key=id_getter)

out = []
for _,i in gp:
    subdict = defaultdict(list)
    for j in i:
        for k,v in j.items():
            subdict[k].append(v)
    out.append(dict(subdict))

out

使用复杂的数据类型,如嵌套列表和字典,我建议真正使用collectionsitertools提供的API

import pandas as pd    
df = pd.DataFrame(raw_list)
dd = pd.concat([df.groupby('id')['item_name'].apply(list), df.groupby('id').['total'].apply(sum)], axis=1).reset_index()
dd.to_dict('records')

您可以使用pandas按分组,并将函数应用于两列,然后转换为dict

[{'id': 12, 'item_name': ['orange', 'apple'], 'total': 2.0},
 {'id': 34, 'item_name': ['apple'], 'total': 22.0}]

类似这样的东西-特殊的调味品是isinstance东西,以确保将连接的值改为列表

请注意,这假定原始列表是由comp_keyid)排序的,如果不是这样,则会出现错误行为

raw_list = [
    {"item_name": "orange", "id": 12, "total": 2},
    {"item_name": "apple", "id": 12},
    {"item_name": "apple", "id": 34, "total": 22},
]

comp_key = "id"
conc_key = "item_name"
grouped_items = []
for item in raw_list:
    last_group = grouped_items[-1] if grouped_items else None
    if not last_group or last_group[comp_key] != item[comp_key]:  # Starting a new group?
        grouped_items.append(item.copy())  # Shallow-copy the item into the result array
    else:
        if not isinstance(last_group[conc_key], list):
            # The concatenation key is not a list yet, make it so
            last_group[conc_key] = [last_group[conc_key]]
        last_group[conc_key].append(item[conc_key])
print(grouped_items)

相关问题 更多 >