11

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.

CurtLH
  • 2,329
  • 4
  • 41
  • 64

3 Answers3

22

Shortest way:

dict(zip(inv[::2], inv[1::2]))
min2bro
  • 4,509
  • 5
  • 29
  • 55
2

Another option using zip:

dict([(x, y) for x, y in zip(inv[::2], inv[1::2])])
# {'apples': 2, 'bananas': 7, 'grapes': 4, 'limes': 10, 'oranges': 3}

Or as @DSM suggested:

dict(zip(inv[::2], inv[1::2]))
# {'apples': 2, 'bananas': 7, 'grapes': 4, 'limes': 10, 'oranges': 3}
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

The key is to use the pairwise iteration and call dict() constructor on the resulting list of pairs, which would create a dictionary using first items as keys and second as values:

Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

Sample:

>>> inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4]
>>> dict(pairwise(inv))
{'grapes': 4, 'bananas': 7, 'apples': 2, 'oranges': 3, 'limes': 10}

where pairwise() function is taken from this answer:

from itertools import izip

def pairwise(iterable):
    a = iter(iterable)
    return izip(a, a)

Python3 version:

def pairwise(iterable):
    a = iter(iterable)
    return zip(a, a)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195