Sometimes, we want to convert [key1,val1,key2,val2] to a dict with Python.
In this article, we’ll look at how to convert [key1,val1,key2,val2] to a dict with Python.
How to convert [key1,val1,key2,val2] to a dict with Python?
To convert [key1,val1,key2,val2] to a dict with Python, we can use the itertools module’s izip function.
For instance, we write
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
to call iter to convert list a into an iterator.
Then we call izip with i for both arguments to zip the even and odd index entries together.
And then we call dict to convert the iterator to a dict.
Conclusion
To convert [key1,val1,key2,val2] to a dict with Python, we can use the itertools module’s izip function.