开发者

single list to dictionary

开发者 https://www.devze.com 2023-01-22 14:56 出处:网络
开发者_开发知识库I have this list: single = [\'key1\', \'value1\', \'key2\', \'value2\', \'key3\', \'value3\']

开发者_开发知识库I have this list:

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

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

Thanks.


>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(single[::2], single[1::2]))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}


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'}


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'}
>>> 


L = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
d = dict(L[n:n+2] for n in xrange(0, len(L), 2))


>>> 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 ;)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号