0

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?

2
  • 4
    Could you please post the code you've tried as well as clarify your objective? Stack Overflow does not simply code for you. Commented Feb 15, 2017 at 23:18
  • 1
    I guess you have your answer now so I'll just point out that using dict, which is a builtin, as a variable name is not good practice and can cause problems elsewhere in your code. Commented Feb 15, 2017 at 23:25

2 Answers 2

3

Here's one way to do it using a list comprehension:

lst = [{'ex1': j, 'ex2': i} for i in y for j in x]

If the list items are strings, you'll get:

print(lst)
# [{'ex2': 'c', 'ex1': 'a'}, {'ex2': 'c', 'ex1': 'b'}, {'ex2': 'd', 'ex1': 'a'}, {'ex2': 'd', 'ex1': 'b'}]
Sign up to request clarification or add additional context in comments.

Comments

-1

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)
        )
    )
)

9 Comments

your formatting is unconventional and makes this code almost impossible to read.
Please at least try to stick to Python style conventions. In Python, a comprehension is almost always better than an equivalent 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...
thanks Paul for pointing this out. I thought about it a lot how to format multiple nested maps, and this was the most clear I could come up with. but I would be extremely grateful if you could show me a better way (just put this in a pastebin, if you have 2 minutes for me)
The answer is don't use multiple maps.
Also just use string literals 'ex1' and 'ex2' rather than trying to be clever with enumerate.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.