Single Dictionary List

I have this list:

single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']

What is the best way to create a dictionary from this?

Thank.

+3
source share
6 answers

Like the SilentGhost solution, without creating 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'}
+7
source
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(single[::2], single[1::2]))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
+9
source

. wizardry , ..

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

:

>>> 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'}
>>> 
+2
L = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
d = dict(L[n:n+2] for n in xrange(0, len(L), 2))
0
>>> single = ['key', 'value', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(*[iter(single)]*2))
{'key3': 'value3', 'key2': 'value2', 'key': 'value'}

, ;)

0

You did not specify any criteria for "best." If you want to understand simplicity, it is easily modified to check for duplicates and an odd number of inputs, it works with any iterable (in case you cannot know the length in advance), NO ADDITIONAL MEMORY IS USED ... try the following:

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
0
source

All Articles