开发者

converting a simple list to a dictionary (in python)

开发者 https://www.devze.com 2023-02-15 16:20 出处:网络
I\'m learning python. I have a list of simple entries and I want to convert it in a di开发者_Go百科ctionary where the first element of list is the key of the second element, the third is the key of th

I'm learning python. I have a list of simple entries and I want to convert it in a di开发者_Go百科ctionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it?

list = ['first_key', 'first_value', 'second_key', 'second_value']

Thanks in advance!


The most concise way is

some_list = ['first_key', 'first_value', 'second_key', 'second_value']
d = dict(zip(*[iter(some_list)] * 2))


myDict = dict(zip(myList[::2], myList[1::2]))

Please do not use 'list' as a variable name, as it prevents you from accessing the list() function.

If there is much data involved, we can do it more efficiently using iterator functions:

from itertools import izip, islice
myList = ['first_key', 'first_value', 'second_key', 'second_value']
myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2)))


If the list is large, you end up wasting memory by building slices or eager zips. One way to convert the list more lazily is to (ab)use the list iterator and izip.

from itertools import izip

lst = ['first_key', 'first_value', 'second_key', 'second_value']
i = iter(lst)
d = dict(izip(i,i))


The KISS way:

Use exception and iterators

    myDict = {}

    it = iter(list) 

    for x in list:
        try:
            myDict[it.next()] = it.next()
        except:
            pass



    myDict
0

精彩评论

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