newbie94
newbie94

Reputation: 63

How can I create a dictionary from a list of string?

So, I have this, for example:

['Apple', 'Red', 'Banana', 'Yellow']

and I need to return

 {'Apple': 'Red', 'Banana': 'Yellow'}

Is there a way to do this?

Upvotes: 1

Views: 44

Answers (3)

tynn
tynn

Reputation: 39843

If it's a list like [k1, v1, k2, v2, ...] just use slicing and zip:

>>> l = ['Apple', 'Red', 'Banana', 'Yellow']
>>> dict(zip(l[::2], l[1::2]))
{'Banana': 'Yellow', 'Apple': 'Red'}

Like this you first create two list, one containing the keys, the other containing the values:

>>> k, v = l[::2], l[1::2]
>>> k
['Apple', 'Banana']
>>> v
['Red', 'Yellow']

Then zip creates an iterator of tuples (pairs of key and value in this case):

>>> list(zip(k, v))
[('Apple', 'Red'), ('Banana', 'Yellow')]

This iterator then can be used to create the dictionary.

Upvotes: 1

Mahmoud Elgindy
Mahmoud Elgindy

Reputation: 114

For Python 3.x you can just use the dict comprehension syntax

d = {key: value for (key, value) in item}

you can use the item in any way you want.

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

Just slice the list and use dict :

>>> li=['Apple', 'Red', 'Banana', 'Yellow']
>>> dict((li[:2],li[2:]))
{'Apple': 'Red', 'Banana': 'Yellow'}

Upvotes: 1

Related Questions