How to use list comprehension to add an element to copies of a dictionary?

让人想犯罪 __ 提交于 2020-01-10 10:09:26

问题


given:

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'}]

I know I can do this:

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.


回答1:


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

or (to use k):

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


来源:https://stackoverflow.com/questions/3197342/how-to-use-list-comprehension-to-add-an-element-to-copies-of-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!