Categories
Python Answers

How to convert [key1,val1,key2,val2] to a dict with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *