Thais Maiolino
Thais Maiolino

Reputation: 1

Combine 2 list in python

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?

Upvotes: 0

Views: 101

Answers (2)

deeenes
deeenes

Reputation: 4576

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

Upvotes: -1

Moses Koledoye
Moses Koledoye

Reputation: 78546

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'}]

Upvotes: 3

Related Questions