如何使用列表推导式向字典的副本添加元素?

19 投票
1 回答
11692 浏览
提问于 2025-04-16 00:57

给定:

template = {'a': 'b', 'c': 'd'}
add = ['e', 'f']
k = 'z'

我想用列表推导式来生成

[{'a': 'b', 'c': 'd', 'z': 'e'},
 {'a': 'b', 'c': 'd', 'z': 'f'}]

我知道我可以这样做:

out = []
for v in add:
  t = template.copy()
  t[k] = v
  out.append(t)

但是这样写有点啰嗦,而且并没有比我想要替换的方式更好。

这个稍微更一般的关于合并字典的问题有点相关,但大体上是说不要这样做。

1 个回答

31
[dict(template,z=value) for value in add]
[dict(template,**{k:value}) for value in add]

或者(用 k 来表示):

撰写回答