下式给出:
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有点相关,但或多或少说不。
答案 0 :(得分:17)
[dict(template,z=value) for value in add]
或(使用k
):
[dict(template,**{k:value}) for value in add]