Manzoor Manzoor - 19 days ago 7
Python Question

Convert list pairwise to dictionaries?

I have a list, and I'd like to convert it into a list of dictionaries in Python.

My list is:

a = ["a", "b", "c", "d", "e", "f"]


I'd like to convert it something like this:

[
{'Key': 'a', 'Value': 'b'},
{'Key': 'c', 'Value': 'd'},
{'Key': 'e', 'Value': 'f'}
]

Answer

zip and a list comprehension are the way to go:

>>> a = ["a","b","c","d","e","f"]
>>> [{'key': k, 'value': v} for k, v in zip(a[::2], a[1::2])]
[{'value': 'b', 'key': 'a'}, {'value': 'd', 'key': 'c'}, {'value': 'f', 'key': 'e'}]

Notice how the list is sliced with a step of two starting at 0 and 1 and then zipped.