如何将包含列表的字典列表合并为单个字典
合并字典列表并合并相同键的列表值
你用update()方法的问题在于:这个方法遇到相同键时会直接用新字典的键值对覆盖原有内容,所以最终all_dict['c']只会保留最后一个字典里的列表,而不是合并所有字典中对应键的列表元素。
下面是两种满足需求的实现方案:
方案1:直接合并列表(保留重复元素)
dictionary_list = [{'a':'string','b':'string','c':['string1','string2']},{'a':'string','b':'string','c':['string1','string2', 'string3']}] all_dict = {} for d in dictionary_list: for key, value in d.items(): if key not in all_dict: # 键不存在时直接赋值,列表做浅拷贝避免原列表修改影响结果 all_dict[key] = value.copy() if isinstance(value, list) else value else: if isinstance(value, list): # 列表类型则追加所有元素 all_dict[key].extend(value) # 非列表类型(如示例中的字符串),若值相同则无需处理;若值不同可根据需求修改逻辑,比如替换或收集为列表 print(all_dict)
输出结果:
{'a': 'string', 'b': 'string', 'c': ['string1', 'string2', 'string1', 'string2', 'string3']}
方案2:合并列表并去重(保持元素顺序)
如果需要去掉重复的列表元素,可以修改列表合并的逻辑:
dictionary_list = [{'a':'string','b':'string','c':['string1','string2']},{'a':'string','b':'string','c':['string1','string2', 'string3']}] all_dict = {} for d in dictionary_list: for key, value in d.items(): if key not in all_dict: all_dict[key] = value.copy() if isinstance(value, list) else value else: if isinstance(value, list): # 遍历新列表元素,仅添加未存在的项 for item in value: if item not in all_dict[key]: all_dict[key].append(item) print(all_dict)
输出结果:
{'a': 'string', 'b': 'string', 'c': ['string1', 'string2', 'string3']}
逻辑说明
- 双层循环遍历所有字典的键值对
- 针对每个键:
- 若未在结果字典中,直接添加(列表做浅拷贝避免后续关联修改)
- 若已存在,根据值的类型处理:列表类型执行合并操作,非列表类型可根据实际需求选择保留原值、替换或收集为列表
内容的提问来源于stack exchange,提问作者Patryk
相关产品推荐
相关产品推荐

