我们如何合并两个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'}热门推荐
10 分别发的祝福语简短
11 大外甥高考祝福语简短
12 小学毕业校长简短祝福语
13 搞工程发财祝福语简短
14 冬季祝福语男生文案简短
15 同事生子问候祝福语简短
16 退休文案寄语简短祝福语
17 送给自己的祝福语简短
18 简短祝福语毛笔字