如何从另一个字典的值创建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'}