jackcogdill
jackcogdill

Reputation: 5132

Converting two lists to a list of dictionaries in Python

I have two lists for example like this:

L = [1, 2]
S = ['B', 'C']

How can I get them to be combined into a dictionary like this:

X = {'B': 1, 'C': 2}

The lists will always be the same length, but can have any amount of items.

Upvotes: 2

Views: 2683

Answers (2)

9000
9000

Reputation: 40904

This way:

>>> key_list = ['a', 'b']
>>> value_list = [1, 2]
>>> result = dict(zip(key_list, value_list))
>>> print result
{'a': 1, 'b': 2}
>>> _

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251618

It's a one-liner:

dict(zip(S, L))

Upvotes: 7

Related Questions