Dictionary list: even elements as keys, odd elements as values

I am trying to use Python to convert listto dictionary, and I need to help come up with a simple solution. The list I would like to convert is as follows:

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

I want to create dictionaryfrom this listwhere the elements in even positions (apples, oranges, limes, bananas, grapes) are keys, and the elements in odd positions (2, 3, 10, 7, 4) are values.

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

I tried using something like enumerateto calculate the position of an element, and then if it is equal, set it as key. But then I'm not sure how to match the next number with its correct element.

+4
source share
3 answers

The shortest way:

dict(zip(inv[::2], inv[1::2]))
+9
source

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

Each element in iterable must be iterable with exactly two objects. The first object of each element is the key in the new dictionary, and the second object is the corresponding value.

Example:

>>> 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 the pairwise()function is taken from this answer :

from itertools import izip

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

Another option with 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}
+1
source

All Articles