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.
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.
Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.
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.
[dict(template,z=value) for value in add]
or (to use k
):
[dict(template,**{k:value}) for value in add]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With