I have 2 lists:
x = [a,b]
y = [c,d]
and I want to create a list of dictionary like this:
dict = [{ex1:a,ex2:c},{ex1:b,ex2:c},{ex1:a,ex2:d},{ex1:b,ex2:d}]
How can I do that in a simple way?
There is a package called itertools which provides many methods to make this kind of things easy. I assume you might have not only one list, but eventually more, so you can put them in another list my_lists, take their product, and the rest of the thing is just making it a dict in the desired format, i.e. with keys like ex1.
Edit:
Here is the same with list comprehension:
[dict(('ex%u' % (i[0] + 1), i[1]) for i in enumerate(co))
for co in itertools.product(*my_lists)]
And was like this with map:
import itertools
x = ['a', 'b']
y = ['c', 'd']
my_lists = [x, y]
list_of_dicts = (
list(
map(
lambda co:
dict(
map(
lambda i:
('ex%u' % (i[0] + 1), i[1]),
enumerate(co)
)
),
itertools.product(*my_lists)
)
)
)
map with lambda from a readability perspective, and will likely perform better too. For the record, I did not downvote, since this does add a valuable generalization with product... just improve the style...'ex1' and 'ex2' rather than trying to be clever with enumerate.
dict, which is a builtin, as a variable name is not good practice and can cause problems elsewhere in your code.