如何从另一个字典的值创建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 训练狗狗捡东西