我们如何合并两个Python字典?
在Python3.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() # start with x's keys and values
z.update(y) # modify z with y's keys and values
return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)这将给出输出:
{'foo': 125, 'bar': 'hello'}热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西