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

你可以通过使用 copy 和 update 函数来合并字典。

示例

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'}

更新于:17-Jun-2020

2 千次观看

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.