You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个字典列表?Python字典列表合并问题求助

问题:合并两个等长字典列表的对应元素

给定两个长度相等的字典列表:

l1 = [{'a': 'foo'}, {'a': 'foo'}, {'a': 'bar'}, {'a': 'bar'}]
l2 = [{'b': 'foo'}, {'b': 'bar'}, {'b': 'foo'}, {'b': 'bar'}]

需要将两个列表中同一索引位置的字典合并,得到目标列表:

l3 = [{'a': 'foo', 'b': 'foo'}, {'a':'foo', 'b':'bar'}, {'a':'bar', 'b':'foo'}, {'a':'bar', 'b':'bar'}]

尝试的代码及错误结果:

l3 = [] 
mydict = {} 
index = 0 
while index < len(l1):     
    mydict['a'] = l1[index]['a']     
    mydict['b'] = l2[index]['b']     
    l3.append(mydict)     
    index +=1

返回结果:

[{'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}]

错误原因

你只创建了一个字典对象mydict,每次循环只是修改这个字典的键值对,然后把它的引用添加到l3中。最终l3里的所有元素都指向同一个字典,所以最后一次循环的修改会覆盖之前所有的内容。

正确实现方法

方法1:循环内新建字典

每次循环都创建一个新的字典,避免引用复用:

l3 = []
index = 0
while index < len(l1):
    mydict = {}  # 每次循环初始化新字典
    mydict['a'] = l1[index]['a']
    mydict['b'] = l2[index]['b']
    l3.append(mydict)
    index += 1

方法2:列表推导式+字典合并(简洁写法)

利用zip配对两个列表的对应元素,结合字典解包生成新字典:

# Python 3.5+ 支持字典解包
l3 = [{**d1, **d2} for d1, d2 in zip(l1, l2)]

如果使用Python 3.9及以上版本,还可以用字典合并操作符|:

l3 = [d1 | d2 for d1, d2 in zip(l1, l2)]

这两种方法都会在每次迭代时生成一个新的字典,确保l3中的每个元素都是独立的对象,不会互相覆盖。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:55:16