Convert [key1,val1,key2,val2] to a dict?
b = dict(zip(a[::2], a[1::2]))
If a
is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()
and len()
, which would normally be a code smell.
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()
method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()
is already lazy in Python 3 so you don't need izip()
.
i = iter(a)
b = dict(zip(i, i))
In Python 3.8 and later you can write this on one line using the "walrus" operator (:=
):
b = dict(zip(i := iter(a), i))
Otherwise you'd need to use a semicolon to get it on one line.
Simple answer
Another option (courtesy of Alex Martelli - source):
dict(x[i:i+2] for i in range(0, len(x), 2))
Related note
If you have this:
a = ['bi','double','duo','two']
and you want this (each element of the list keying a given value (2 in this case)):
{'bi':2,'double':2,'duo':2,'two':2}
you can use:
>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}
You can use a dict comprehension for this pretty easily:
a = ['hello','world','1','2']
my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
This is equivalent to the for loop below:
my_dict = {}
for index, item in enumerate(a):
if index % 2 == 0:
my_dict[item] = a[index+1]