David542
David542

Reputation: 110382

How to do an inverse zip operation

I can use zip to get a dictionary like so:

l1 = ['Director', 'peter jackson']
l2 = [u'Title', u'Lord of the Rings: The Two Towers']
dict(zip(l1,l2))

How would I get the same dict with the following two structures?

l1 = ['Director', 'Title']
l2 = [u'peter jackson', u'Lord of the Rings: The Two Towers']

Upvotes: 1

Views: 87

Answers (2)

KSFT
KSFT

Reputation: 1774

In your first example, dict(zip(l1,l2)) will give you the dict {'Director':u'Title','peter jackson':u'Lord of the Rings: The Two Towers'}.

In your second example, dict(zip(l1,l2)) will give you what you probably want: {'Director':u'peter jackson','Title':u'Lord of the Rings: The Two Towers'}

Assuming you wanted the second one from both, you can just call dict() on the two lists from the first example:

dict([l1,l2])

You already know how to get that dict from the first example.

If you didn't make a mistake in your question, you can just zip() the two lists in your second example to get the two from your first example, then call dict() on those:

dict(zip(l1,l2))

Upvotes: 2

kichik
kichik

Reputation: 34734

Assuming you flipped the examples as the comments say, it looks like you're looking for:

l1 = ['Director', 'peter jackson']
l2 = [u'Title', u'Lord of the Rings: The Two Towers']
dict([l1, l2])
# {'Director': 'peter jackson', u'Title': u'Lord of the Rings: The Two Towers'}

dict() can also take a list of key value pairs.

Upvotes: 0

Related Questions