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 zip and dict functions.
For instance, we write:
a = ['foo', 1, 'bar', 2]
b = dict(zip(a[::2], a[1::2]))
print(b)
We call zip with the slices a that returns the keys and values.
We get all the keys with a[::2].
And we get all the values with a[1::2].
Then we call zip to combine them into a list of key-value tuples.
And then we call dict to convert the list of tuples into a dictionary.
Therefore, b is {'foo': 1, 'bar': 2}.
Conclusion
To convert [key1,val1,key2,val2] to a dict with Python, we can use the zip and dict functions.