Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 388
BCS Avatar asked Jul 07 '10 17:07

BCS


People also ask

Can we use list comprehension in dictionary?

Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

Does list comprehension create a copy?

Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.

Can you append in list comprehension Python?

Note: Python also offers other kinds of comprehensions, such as set comprehensions, dictionary comprehensions, and generator expressions. To turn . append() into a list comprehension, you just need to put its argument followed by the loop header (without the colon) inside a pair of square brackets.


1 Answers

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

or (to use k):

[dict(template,**{k:value}) for value in add]
like image 149
unutbu Avatar answered Sep 28 '22 11:09

unutbu