如何合并两个Python字典?
在Python 3.5+中,您可以使用**操作符来解包一个字典,然后使用以下语法组合多个字典:
a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c)
这将会输出:
{'foo': 125, 'bar': 'hello'}
在旧版本中并不支持此方法。不过,您可以使用类似下面的语法来代替:
a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c)
这将会输出:
{'foo': 125, 'bar': 'hello'}
另外,您还可以使用复制和更新函数来合并字典。例如,
def merge_dicts(x, y):
z = x.copy() # 以x的键和值为起点
z.update(y) # 使用y的键和值修改z
return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)
这将会输出:
{'foo': 125, 'bar': 'hello'}
更多Python相关文章,请阅读:Python 教程
极客教程