green_bean_4_u green_bean_4_u - 4 months ago 22
Python Question

List to Dictionary: Even items as keys, odd items as values

I am trying to use Python to convert a

list
into a
dictionary
and I need to help coming up with a simple solution. The list that I would like to convert looks like this:

inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4]


I want to create a
dictionary
from this
list
, where the items in the even positions (apples, oranges, limes, bananas, grapes) are the
keys
, and the items in the odd positions (2, 3, 10, 7, 4) are the
values
.

inv_dict = {'apples':2, 'oranges':3, 'limes':10, 'bananas':7, 'grapes':4}


I've tried using something like
enumerate
to count the position of the item, and then if it's even, set it as a
key
. But then I'm not sure how to match the following number up with it's correct item.

Answer

Shortest way:

dict(zip(inv[::2], inv[1::2]))
Comments