views:

127

answers:

6

I have this list:

single = ['key', 'value', 'key', 'value', 'key', 'value']

What's the best way to create a dictionary from this?

Thanks.

+2  A: 

This is the simplest I guess. You will see more wizardry in solution here using list comprehension etc

dictObj = {}
for x in range(0, len(single), 2):
    dictObj[single[x]] = single[x+1]

Output:

>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dictObj = {}
>>> for x in range(0, len(single), 2):
...     dictObj[single[x]] = single[x+1]
... 
>>> 
>>> dictObj
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
>>> 
pyfunc
+1: Could also do a list comp: `dict([(single[x], single[x+1]) for x in range(0, len(s), 2)])`
sdolan
+9  A: 
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(single[::2], single[1::2]))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
SilentGhost
`timeit`'d it, runs 2 times faster than a dict comprehension inspired by pyfunc's answer (which in turn beats a list-of-tuple comprehension) o.O +1 since it's also the simplest solution.
delnan
A: 
L = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
d = dict(L[n:n+2] for n in xrange(0, len(L), 2))
nosklo
+5  A: 

Similar to SilentGhost's solution, without building temporary lists:

>>> from itertools import izip
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> si = iter(single)
>>> dict(izip(si, si))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
pillmuncher
Wow, now that's clever.
kindall
A: 
>>> single = ['key', 'value', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(*[iter(single)]*2))
{'key3': 'value3', 'key2': 'value2', 'key': 'value'}

Probably not the most readable version though ;)

adw
A: 

You haven't specified any criteria for "best". If you want understandability, simplicity, easily modified to check for duplicates and odd number of inputs, works with any iterable (in case you can't find out the length in advance), NO EXTRA MEMORY USED, ... try this:

def load_dict(iterable):
    d = {}
    pair = False
    for item in iterable:
        if pair:
            # insert duplicate check here
            d[key] = item
        else:
            key = item
        pair = not pair
    if pair:
        grumble_about_odd_length(key)
    return d
John Machin