我有一份字典的清单,请看下面
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)
如何解决
您可以使用
itertools.grouper
按id进行分组,并使用collections.defaultdict
将具有相同键的值组合到列表中使用复杂的数据类型,如嵌套列表和字典,我建议真正使用
collections
和itertools
提供的API您可以使用pandas按分组,并将函数应用于两列,然后转换为dict
类似这样的东西-特殊的调味品是
isinstance
东西,以确保将连接的值改为列表请注意,这假定原始列表是由
comp_key
(id
)排序的,如果不是这样,则会出现错误行为相关问题 更多 >
编程相关推荐