Python中如何按键合并字典列表 及如何用reduce()实现该功能
实现方案
语法最简洁的实现方式
使用collections.defaultdict遍历合并即可,代码可读性高且写法简洁:
from collections import defaultdict raw_data = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}] merge_dict = defaultdict(dict) for item in raw_data: for key, val in item.items(): merge_dict[key].update(val) result = [dict(merge_dict)]
执行后result就是要求的目标结构。
基于reduce()的实现方式
需要先导入functools.reduce,通过迭代累加的逻辑完成合并:
易读版本(兼容所有Python3版本)
from functools import reduce raw_data = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}] def merge_step(acc, cur): # 取当前元素唯一的键值对 k, v = next(iter(cur.items())) acc[k] = {**acc.get(k, {}), **v} return acc result = [reduce(merge_step, raw_data, {})]
极简匿名函数版本(Python3.8+支持海象运算符)
from functools import reduce raw_data = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}] result = [reduce(lambda acc, x: {**acc, (k:=next(iter(x.keys()))): {**acc.get(k, {}), **next(iter(x.values()))}}, raw_data, {})]
内容的提问来源于stack exchange,提问作者retr0327
相关产品推荐
相关产品推荐

