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

时间:2010-07-07 17:35:05

标签: python dictionary list-comprehension

下式给出:

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)

但它有点冗长,并且没有我想要取代的优势。

稍微更一般的question on merging dictionaries有点相关,但或多或​​少说不。

1 个答案:

答案 0 :(得分:17)

[dict(template,z=value) for value in add]

或(使用k):

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