19

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.

Community
  • 1
  • 1
BCS
  • 75,627
  • 68
  • 187
  • 294

1 Answers1

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

or (to use k):

[dict(template,**{k:value}) for value in add]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    the ** is for use the dictionary as keyword arguments http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists – Xavier Combelle Jul 07 '10 at 17:45