Convert a simple list to a dictionary (in python)

I am learning python. I have a list of simple entries, and I want to convert it to a dictionary, where the first element of the list is the key of the second element, the third is the key of the fourth, etc. How can i do this?

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

Thanks in advance!

+3
source share
4 answers
myDict = dict(zip(myList[::2], myList[1::2]))

Please do not use the β€œlist” as the variable name, as it does not allow you to access the list () function.

If there is a lot of data, we can do this more efficiently using the 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)))
+2
source

The most concise way is

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

, , . : (ab) izip.

from itertools import izip

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

KISS:

    myDict = {}

    it = iter(list) 

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



    myDict
0

All Articles