如何使用列表理解将元素添加到字典的副本? [英] How to use list comprehension to add an element to copies of a dictionary?

查看:115
本文介绍了如何使用列表理解将元素添加到字典的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

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

我想使用列表解析来生成

I want to use list comprehension to generate

[{'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)

但它有点冗长,没有比我想要替换的优势。

but it is a little verbose and has no advantage over what I'm trying to replace.

这个稍微更一般的问题合并词典有些相关,但多或少说不要。

This slightly more general question on merging dictionaries is somewhat related but more or less says don't.

推荐答案

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

或(使用 k ): p>

or (to use k):

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

这篇关于如何使用列表理解将元素添加到字典的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆