我们如何合并两个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 婚前女儿生日祝福语简短